- 示例代码1:
- 示例代码2:
- 总结:
public int Send(int num)
{
switch (num)
{
case 1:
return 101;
case 2:
return 102;
case 3:
return 103;
case 4:
return 104;
default:
return 0;
}
}
可简化为:
public int Send(int num)
{
return num switch
{
1 => 101,
2 => 102,
3 => 103,
4 => 104,
_ => 0,
};
}
示例代码2:
public string test(string a)
{
switch (a)
{
case "a":
return "aa";
default:
return "dd";
}
}
可简化为:
public string test(string a)
{
return a switch
{
"a" => "aa",
_ => "dd",
};
}
总结:
1、不拘束于变量类型 2、符号“_”意思为default 3、需要全部都是返回时才能简化



