是否有一种方法可以通过多个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#中switch的一个不太为人所知的方面是它依赖于操作符=,因为它可以被覆盖,所以你可以有这样的东西:


string s = foo();

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

其他回答

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

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

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

.NET Framework 3.5有如下的范围:

可列举的。范围从MSDN

你可以将它与“contains”和IF语句一起使用,因为有人说SWITCH语句使用“==”操作符。

这里有一个例子:

int c = 2;
if(Enumerable.Range(0,10).Contains(c))
    DoThing();
else if(Enumerable.Range(11,20).Contains(c))
    DoAnotherThing();

但是我认为我们可以有更多的乐趣:因为您不需要返回值,而且这个操作不接受参数,所以您可以轻松地使用操作!

public static void MySwitchWithEnumerable(int switchcase, int startNumber, int endNumber, Action action)
{
    if(Enumerable.Range(startNumber, endNumber).Contains(switchcase))
        action();
}

这个新方法的旧示例:

MySwitchWithEnumerable(c, 0, 10, DoThing);
MySwitchWithEnumerable(c, 10, 20, DoAnotherThing);

因为你传递的是动作,而不是值,所以你应该省略圆括号,这很重要。如果需要带参数的函数,只需将Action的类型更改为Action<ParameterType>。如果需要返回值,请使用Func<ParameterType, ReturnType>。

在c# 3.0中,没有简单的局部应用程序来封装case参数相同的事实,但您可以创建一个小的辅助方法(虽然有点啰嗦)。

public static void MySwitchWithEnumerable(int startNumber, int endNumber, Action action){ 
    MySwitchWithEnumerable(3, startNumber, endNumber, action); 
}

这里有一个例子,说明新的函数导入语句如何比旧的命令式语句更强大和优雅。

为此,您将使用goto语句。如:

    switch(value){
    case 1:
        goto case 3;
    case 2:
        goto case 3;
    case 3:
        DoCase123();
    //This would work too, but I'm not sure if it's slower
    case 4:
        goto case 5;
    case 5:
        goto case 6;
    case 6:
        goto case 7;
    case 7:
        DoCase4567();
    }

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

case 1: case 2: case 3:
   break;

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

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

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