示例代码1:
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",
};
}
示例代码3:
public void Send(int num)
{
switch (num)
{
case 1:
SendMsg = 101;
break;
case 2:
SendMsg = 102;
break;
case 3:
SendMsg = 103;
break;
case 4:
SendMsg = 104;
break;
default:
SendMsg = 100;
break;
}
}
可简化为:
public void Send(int num)
{
SendMsg = num switch
{
1 => 101,
2 => 102,
3 => 103,
4 => 104,
_ => 100,
};
}
总结:
1、不拘束于变量类型
2、符号“_”意思为default
|