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:我可以使用一个范围而不是一个数字吗


基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01