是否有一种方法可以通过多个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#我已经这样做了

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

其他回答

下面的代码将无法工作:

case 1 | 3 | 5:
// Not working do something

做到这一点的唯一方法是:

case 1: case 2: case 3:
// Do something
break;

您正在寻找的代码在Visual Basic中工作,您可以轻松地将范围…在switch语句的none选项中,或者如果else blocks方便,我建议,在非常极端的情况下,用Visual Basic生成.dll,然后导入回c#项目中。

注意:在Visual Basic中等效的开关是“选择大小写”。

gcc实现了对C语言的扩展,以支持顺序范围:

switch (value)
{
   case 1...3:
      //Do Something
      break;
   case 4...6:
      //Do Something
      break;
   default:
      //Do the Default
      break;
}

编辑:刚刚注意到这个问题上有c#标签,所以gcc的答案可能没有帮助。

如果你有非常大量的字符串(或任何其他类型)的情况下都做同样的事情,我建议使用字符串列表结合字符串。包含属性。

如果你有一个大的switch语句

switch (stringValue)
{
    case "cat":
    case "dog":
    case "string3":
    ...
    case "+1000 more string": // Too many string to write a case for all!
        // Do something;
    case "a lonely case"
        // Do something else;
    .
    .
    .
}

你可能想用这样的if语句替换它:

// Define all the similar "case" string in a List
List<string> listString = new List<string>(){ "cat", "dog", "string3", "+1000 more string"};
// Use string.Contains to find what you are looking for
if (listString.Contains(stringValue))
{
    // Do something;
}
else
{
    // Then go back to a switch statement inside the else for the remaining cases if you really need to
}

这适用于任意数量的字符串情况。

c#中switch的一个不太为人所知的方面是它依赖于操作符=,因为它可以被覆盖,所以你可以有这样的东西:


string s = foo();

switch (s) {
  case "abc": /*...*/ break;
  case "def": /*...*/ break;
}

另一种选择是使用例行程序。如果案例1-3都执行相同的逻辑,那么将该逻辑包装在一个例程中,并为每个案例调用它。我知道这实际上并没有摆脱case语句,但它确实实现了良好的风格,并将维护保持在最低限度.....

[编辑]增加了匹配原始问题的替代实现…[/编辑]

switch (x)
{
   case 1:
      DoSomething();
      break;
   case 2:
      DoSomething();
      break;
   case 3:
      DoSomething();
      break;
   ...
}

private void DoSomething()
{
   ...
}

Alt

switch (x)
{
   case 1:
   case 2:
   case 3:
      DoSomething();
      break;
   ...
}

private void DoSomething()
{
   ...
}