C# 模式匹配里应该注意的几点
马上就要出C#11了,近几个版本模式匹配一直在更新,参见官网:模式 - C# 参考 | Microsoft Learn
使用模式主要就是switch, 分两种 switch 语句和表达式,
语句:(功能全面)
switch(i){
case const_exp1: /*customer logic*/ break;
case const_exp2: /*customer logic*/ break;
//...
default /*customer logic*/ break;
}
表达式:(需要有返回值)
x=i switch{
const_exp1=>/*customer expression*/,
const_exp2=>/*customer expression*/,
//...
_=>/*customer expression*/,
};
需要特别指出值得注意的是
1,常量声明式就是等于的意思
2,关系模式(>,>=,<,<=): 由关系运算左置来表达,注意此关系模式中不包括==,!= , ==这个直接属于声明模式,!= 则属于 not 逻辑模式之列
3,模式匹配,依赖于常量表达式,否则需要启用写法比较冗余 难看的 when子句,when子句相当于一个一般逻辑表达式,范围全面但写法冗余最好别用