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 thewhencondition, but are used in this example to highlight the comparison(s). varmay also be used in lieu ofint. For example:case var n when n >= 100:.
这篇关于Switch case:我可以使用一个范围而不是一个数字吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Switch case:我可以使用一个范围而不是一个数字吗
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
