Switch case: can I use a range instead of a one number(Switch case:我可以使用一个范围而不是一个数字吗)
问题描述
我想用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:
.
这篇关于Switch case:我可以使用一个范围而不是一个数字吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Switch case:我可以使用一个范围而不是一个数字吗


- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01