我想用switch,但是我的case比较多,有什么捷径吗?到目前为止,我知道并尝试过的唯一解决方案是:
switch (number)
{
case 1: something; break;
case 2: other thing; break;
...
case 9: .........; break;
}
我希望我能做的是:
switch (number)
{
case (1 to 4): do the same for all of them; break;
case (5 to 9): again, same thing for these numbers; break;
}
C# 7 的原始答案
这个问题有点晚了,但在最近的变化中 introduced in C# 7 (在 Visual Studio 2017/.NET Framework 4.6.2 中默认可用),现在可以使用 switch
语句进行基于范围的切换。
示例:
int i = 63;
switch (i)
{
case int n when (n >= 100):
Console.WriteLine($"I am 100 or above: {n}");
break;
case int n when (n < 100 && n >= 50 ):
Console.WriteLine($"I am between 99 and 50: {n}");
break;
case int n when (n < 50):
Console.WriteLine($"I am less than 50: {n}");
break;
}
注意事项:
- 括号
(
和 )
在 when
条件中不是必需的,但在此示例中用于突出显示比较.
var
也可以用来代替 int
。例如:case var n when n >= 100:
。
C# 9 的更新示例
switch(myValue)
{
case <= 0:
Console.WriteLine("Less than or equal to 0");
break;
case > 0 and <= 10:
Console.WriteLine("More than 0 but less than or equal to 10");
break;
default:
Console.WriteLine("More than 10");
break;
}
或
var message = myValue switch
{
<= 0 => "Less than or equal to 0",
> 0 and <= 10 => "More than 0 but less than or equal to 10",
_ => "More than 10"
};
Console.WriteLine(message);