c# - 开关盒 : can I use a range instead of a one number

标签 c# switch-statement

<分区>

我想用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);

关于c# - 开关盒 : can I use a range instead of a one number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20147879/

相关文章:

c# - .NET 示例 VCF 阅读器

C++:根据变量将同一对象实例化为多种类型之一

c - 开关 - 默认不在 C 中工作

java - try catch 和用户输入

c# - 以编程方式添加边界字段

c# - 来自本地资源的字体系列资源

c# - Slickgrid 为单元格/列或行添加颜色

c# - 将类型约束到接口(interface)的目的是什么?

java - 使用 switch 语句创建 try-catch 的问题

Javascript switch 语句根据情况执行一些相同的功能