C# switch/break

Deadly 提交于 2019-12-04 00:14:09
Guffa

Yes, you can fall through to the next case block in two ways. You can use empty cases, which don't need a break, or you can use goto to jump to the next (or any) case:

switch (n) {
  case 1:
  case 2:
  case 3:
    Console.WriteLine("1, 2 or 3");
    goto case 4;
  case 4:
    Console.WriteLine(4);
    break;
}

The enforcement of "break" is there to stop bugs. If you need to force a fall-thru then use "goto case " (replace the with appropriate value)

the following example shows what you can do:

switch(n)
{
    case 1:
    case 2:
      //do something for 1+2
      //...
      goto case 3;
    case 3:
      //do something for 3, and also extra for 1+2
      //...
      break;
    default:
      //do something for all other values
      //...
      break;
}

See http://msdn.microsoft.com/en-us/library/06tc147t%28VS.80%29.aspx

C# doesn't support implicit fall through construct, but the break (or goto) nonetheless has to be there (msdn). The only thing you can do is stack cases in the following manner:

switch(something) {
    case 1:
    case 2:
      //do something
      break;
    case 3:
      //do something else
}

but that break (or another jump statement like goto) just needs to be there.

In my C# (.NET 1.1, CF) code, both of these are allowed:

switch (_printerChoice) 
{
    case BeltPrintersEnum.ZebraQL220: 
        return new ZebraQL220Printer();
        break;
    case BeltPrintersEnum.ONeal: 
        return new ONealPrinter();
        break;
    default:            
        return new ZebraQL220Printer();         
                        break;  
}

switch (_printerChoice) 
{
    case BeltPrintersEnum.ZebraQL220: 
        return new ZebraQL220Printer();
    case BeltPrintersEnum.ONeal: 
        return new ONealPrinter();
    default:            
        return new ZebraQL220Printer();         
}

...but with the breaks in, they are grayed out, so considered moot. So, at least in my case, they are allowed but not required.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!