是否有一种方法可以通过多个case语句而不声明case值:重复?

我知道这很管用:

switch (value)
{
   case 1:
   case 2:
   case 3:
      // Do some stuff
      break;
   case 4:
   case 5:
   case 6:
      // Do some different stuff
      break;
   default:
       // Default stuff
      break;
}

但我想这样做:

switch (value)
{
   case 1,2,3:
      // Do something
      break;
   case 4,5,6:
      // Do something
      break;
   default:
      // Do the Default
      break;
}

这是我从另一种语言中想到的语法,还是我遗漏了什么?


当前回答

在c# 8.0中,您可以使用新的开关表达式语法,这是您的理想情况。

var someOutput = value switch
{
    >= 1 and <= 3 => <Do some stuff>,
    >= 4 and <= 6 => <Do some different stuff>,
    _ => <Default stuff>
};

其他回答

我认为这个在c# 7或更高版本中更好。

switch (value)
{
    case var s when new[] { 1,2 }.Contains(s):
    // Do something
     break;
   
    default:
    // Do the default
    break;
 }

你也可以在c#的开关情况下检查范围:开关情况:我可以使用一个范围而不是一个数字

OR

 int i = 3;

        switch (i)
        {
            case int n when (n >= 7):
                Console.WriteLine($"I am 7 or above: {n}");
                break;

            case int n when (n >= 4 && n <= 6):
                Console.WriteLine($"I am between 4 and 6: {n}");
                break;

            case int n when (n <= 3):
                Console.WriteLine($"I am 3 or less: {n}");
                break;
        }

在c#中切换多个情况

或者如果你想了解基础知识 c#开关箱

c# 7的原始答案

在c# 7中(默认在Visual Studio 2017中可用)。NET Framework 4.6.2),基于范围的切换现在可以通过switch语句实现,这将有助于解决OP的问题。

例子:

int i = 5;

switch (i)
{
    case int n when (n >= 7):
        Console.WriteLine($"I am 7 or above: {n}");
        break;

    case int n when (n >= 4 && n <= 6 ):
        Console.WriteLine($"I am between 4 and 6: {n}");
        break;

    case int n when (n <= 3):
        Console.WriteLine($"I am 3 or less: {n}");
        break;
}

// Output: I am between 4 and 6: 5

注:

括号(和)在when条件中不是必需的,但在本例中用于突出显示比较。 Var也可以用来代替int。例如:case var n when n >= 7:。


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;
}

or

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);

你可以省略换行符,它会给你:

case 1: case 2: case 3:
   break;

但我认为那是不好的风格。

使用新版本的c#我已经这样做了

public string GetValue(string name)
            {
                return name switch
                {
                    var x when name is "test1" || name is "test2" => "finch",
                    "test2" => somevalue,
                    _ => name
                };
            }

为了让c#中最不常用的语法之一看起来更好或工作得更好,似乎已经做了大量的工作。我个人认为switch语句很少值得使用。我强烈建议你分析你正在测试的数据和你想要的最终结果。

让我们举个例子,你想快速测试一个已知范围内的值,看看它们是否是质数。你想要避免让你的代码做浪费的计算,你可以在网上找到你想要的范围内的质数列表。您可以使用一个大型switch语句将每个值与已知素数进行比较。

或者你可以创建一个质数的数组映射,并立即得到结果:

    bool[] Primes = new bool[] {
        false, false, true, true, false, true, false,    
        true, false, false, false, true, false, true,
        false,false,false,true,false,true,false};
    private void button1_Click(object sender, EventArgs e) {
        int Value = Convert.ToInt32(textBox1.Text);
        if ((Value >= 0) && (Value < Primes.Length)) {
            bool IsPrime = Primes[Value];
            textBox2.Text = IsPrime.ToString();
        }
    }

也许你想看看字符串中的一个字符是否是十六进制的。您可以使用一个ungly和有点大的switch语句。

或者你可以使用正则表达式来测试字符,或者使用IndexOf函数在已知的十六进制字母字符串中搜索字符:

        private void textBox2_TextChanged(object sender, EventArgs e) {
        try {
            textBox1.Text = ("0123456789ABCDEFGabcdefg".IndexOf(textBox2.Text[0]) >= 0).ToString();
        } catch {
        }
    }

Let us say you want to do one of 3 different actions depending on a value that will be the range of 1 to 24. I would suggest using a set of IF statements. And if that became too complex (Or the numbers were larger such as 5 different actions depending on a value in the range of 1 to 90) then use an enum to define the actions and create an array map of the enums. The value would then be used to index into the array map and get the enum of the action you want. Then use either a small set of IF statements or a very simple switch statement to process the resulting enum value.

此外,将一系列值转换为操作的数组映射的好处是可以通过代码轻松更改它。使用硬连线代码,你不能轻易地在运行时改变行为,但使用数组映射则很容易。