切换大小写:我可以使用范围而不是一个数字 [英] Switch case: can I use a range instead of a one number
本文介绍了切换大小写:我可以使用范围而不是一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用switch,但是我有很多情况,有没有捷径?到目前为止,我知道并尝试过的唯一解决方案是:
I want to use switch, but I have many cases, is there any shortcut? So far the only solution I know and tried is:
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 (默认情况下在Visual Studio 2017 / .NET Framework 4.6.2中可用),现在可以使用 switch
语句进行基于范围的切换。
A bit late to the game for this question, but in recent changes introduced in C# 7 (Available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the switch
statement.
示例:
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:
。
- The parentheses
(
and)
are not required in thewhen
condition, but are used in this example to highlight the comparison(s). var
may also be used in lieu ofint
. For example:case var n when n >= 100:
.
这篇关于切换大小写:我可以使用范围而不是一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文