【问题标题】:Switch case execute code without breaking C# [duplicate]在不破坏 C# 的情况下切换 case 执行代码 [重复]
【发布时间】:2018-06-21 09:06:57
【问题描述】:

在 C# 中是否可以在不中断的情况下执行 switch case?

这是一个需要使用中断的开关示例

var bar = "Foo";
switch (foo) {
    case 0:
    case 1:
        bar += " Bar";
    case 2:
    case 3:
        Console.WriteLine(bar);
        break;
    default:
        break;
}

这是代码应该产生的:

0: Foo Bar
1: Foo Bar
2: Bar
3: Bar
Else: nothing

是否可以这样做或者我必须这样做:

var bar = "Foo";
if(foo == 0 || foo == 1) bar += " Bar";
switch (foo) {
    case 0:
    case 1:
    case 2:
    case 3:
        Console.WriteLine(bar);
        break;
    default:
        break;
}

【问题讨论】:

    标签: c# switch-statement


    【解决方案1】:

    这称为隐式下降,在 C# 中不支持。

    您可以使用goto case 声明。

    var bar = "Foo";
    switch (foo) {
        case 0:
        case 1:
            bar += " Bar";
            goto case 2;
        case 2:
        case 3:
            Console.WriteLine(bar);
            break;
        default:
            break;
    }
    

    【讨论】:

      【解决方案2】:

      如果switch 大小写在您的代码中不是强制性的,您可以简化您的代码。 你可以试试这样:

      var bar = "Foo";
      if(foo == 0 || foo == 1) bar += " Bar";
      if(foo >= 0 && foo <= 3) //Replacement of switch with single if condition
          Console.WriteLine(bar);
      
      Output:
      if foo == 1 then print -> "Foo Bar"
      if foo == 3 then print -> "Foo"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-08
        • 2017-12-17
        • 2018-03-08
        • 1970-01-01
        • 2013-12-12
        相关资源
        最近更新 更多