Switch语句贯穿是我个人喜欢Switch vs. if/else if结构的主要原因之一。下面是一个例子:

static string NumberToWords(int number)
{
    string[] numbers = new string[] 
        { "", "one", "two", "three", "four", "five", 
          "six", "seven", "eight", "nine" };
    string[] tens = new string[] 
        { "", "", "twenty", "thirty", "forty", "fifty", 
          "sixty", "seventy", "eighty", "ninety" };
    string[] teens = new string[]
        { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
          "sixteen", "seventeen", "eighteen", "nineteen" };

    string ans = "";
    switch (number.ToString().Length)
    {
        case 3:
            ans += string.Format("{0} hundred and ", numbers[number / 100]);
        case 2:
            int t = (number / 10) % 10;
            if (t == 1)
            {
                ans += teens[number % 10];
                break;
            }
            else if (t > 1)
                ans += string.Format("{0}-", tens[t]);
        case 1:
            int o = number % 10;
            ans += numbers[o];

            break;
        default:
            throw new ArgumentException("number");
    }
    return ans;
}

聪明的人畏缩不前,因为字符串[]应该在函数之外声明:好吧,它们是,这只是一个例子。

编译器失败,出现以下错误:

Control cannot fall through from one case label ('case 3:') to another
Control cannot fall through from one case label ('case 2:') to another

为什么?有没有什么方法能让这种行为不需要三个如果呢?


他们为c#改变了switch语句(来自C/Java/ c++)的行为。我想原因是人们忘记了失败,导致了错误。我读过的一本书说使用goto进行模拟,但对我来说这听起来不像是一个好的解决方案。


跳转语句(例如break)是 每个案例块后要求, 包括最后一个块是否 case语句或默认值 声明。只有一个例外,不像 c++的switch语句),c#没有 支撑着一种含蓄的坠落 一个箱子连着另一个箱子。一个 例外是如果case语句有 没有代码。

——c# switch()文档


他们故意省略了这种行为,以避免这种行为不是由意志决定的,而是引起问题的。

它只能在case部分没有语句的情况下使用,例如:

switch (whatever)
{
    case 1:
    case 2:
    case 3: boo; break;
}

开关失效在历史上是现代软件的主要漏洞来源之一。语言设计人员决定强制在case的末尾跳转,除非您默认直接跳转到下一个case而不进行处理。

switch(value)
{
    case 1:// this is still legal
    case 2:
}

你可以“转到案例标签” http://www.blackwasp.co.uk/CSharpGoto.aspx

The goto statement is a simple command that unconditionally transfers the control of the program to another statement. The command is often criticised with some developers advocating its removal from all high-level programming languages because it can lead to spaghetti code. This occurs when there are so many goto statements or similar jump statements that the code becomes difficult to read and maintain. However, there are programmers who point out that the goto statement, when used carefully, provides an elegant solution to some problems...


您忘记在情形3中添加“break;”语句。在情形2中,你把它写到if块中。 因此,试试这个吧:

case 3:            
{
    ans += string.Format("{0} hundred and ", numbers[number / 100]);
    break;
}


case 2:            
{
    int t = (number / 10) % 10;            
    if (t == 1)            
    {                
        ans += teens[number % 10];                
    }            
    else if (t > 1)                
    {
        ans += string.Format("{0}-", tens[t]);        
    }
    break;
}

case 1:            
{
    int o = number % 10;            
    ans += numbers[o];            
    break;        
}

default:            
{
    throw new ArgumentException("number");
}

(复制/粘贴我在其他地方提供的答案)

通过在case中没有代码(见case 0),或使用特殊的goto case(见case 1)或goto default(见case 2)表单,可以实现切换情况:

switch (/*...*/) {
    case 0: // shares the exact same code as case 1
    case 1:
        // do something
        goto case 2;
    case 2:
        // do something else
        goto default;
    default:
        // do something entirely different
        break;
}

“为什么”是为了避免意外摔倒,对此我很感激。这是C和Java中常见的错误来源。

解决办法是使用goto,例如。

switch (number.ToString().Length)
{
    case 3:
        ans += string.Format("{0} hundred and ", numbers[number / 100]);
        goto case 2;
    case 2:
    // Etc
}

在我看来,开关/机箱的总体设计有点不太理想。它太接近C语言了——在范围等方面可以做一些有用的改变。可以说,一个更聪明的开关,可以进行模式匹配等将是有帮助的,但这实际上是从开关到“检查条件序列”的变化-在这一点上,可能需要一个不同的名称。


在每个case语句之后需要break或goto语句,即使它是默认的case。


你可以像c++一样通过goto关键字实现fall through。

EX:

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

为了补充答案,我认为有必要考虑与此相关的相反问题,即:为什么C允许跌倒?

当然,任何编程语言都有两个目标:

为计算机提供指令。 留下程序员意图的记录。

The creation of any programming language is therefore a balance between how to best serve these two goals. On the one hand, the easier it is to turn into computer instructions (whether those are machine code, bytecode like IL, or the instructions are interpreted on execution) then more able that process of compilation or interpretation will be to be efficient, reliable and compact in output. Taken to its extreme, this goal results in our just writing in assembly, IL, or even raw op-codes, because the easiest compilation is where there is no compilation at all.

相反,语言越能表达程序员的意图,而不是为此目的所采取的手段,程序在编写和维护时就越容易理解。

Now, switch could always have been compiled by converting it into the equivalent chain of if-else blocks or similar, but it was designed as allowing compilation into a particular common assembly pattern where one takes a value, computes an offset from it (whether by looking up a table indexed by a perfect hash of the value, or by actual arithmetic on the value*). It's worth noting at this point that today, C# compilation will sometimes turn switch into the equivalent if-else, and sometimes use a hash-based jump approach (and likewise with C, C++, and other languages with comparable syntax).

在这种情况下,允许失败有两个很好的理由:

It just happens naturally anyway: if you build a jump table into a set of instructions, and one of the earlier batches of instructions doesn't contain some sort of jump or return, then execution will just naturally progress into the next batch. Allowing fall-through was what would "just happen" if you turned the switch-using C into jump-table–using machine code. Coders who wrote in assembly were already used to the equivalent: when writing a jump table by hand in assembly, they would have to consider whether a given block of code would end with a return, a jump outside of the table, or just continue on to the next block. As such, having the coder add an explicit break when necessary was "natural" for the coder too.

因此,在当时,平衡计算机语言的两个目标是合理的尝试,因为它既涉及生成的机器代码,也涉及源代码的表达性。

然而,四十年后,情况不太一样了,原因如下:

Coders in C today may have little or no assembly experience. Coders in many other C-style languages are even less likely to (especially Javascript!). Any concept of "what people are used to from assembly" is no longer relevant. Improvements in optimisations mean that the likelihood of switch either being turned into if-else because it was deemed the approach likely to be most efficient, or else turned into a particularly esoteric variant of the jump-table approach are higher. The mapping between the higher- and lower-level approaches is not as strong as it once was. Experience has shown that fall-through tends to be the minority case rather than the norm (a study of Sun's compiler found 3% of switch blocks used a fall-through other than multiple labels on the same block, and it was thought that the use-case here meant that this 3% was in fact much higher than normal). So the language as studied make the unusual more readily catered-to than the common. Experience has shown that fall-through tends to be the source of problems both in cases where it is accidentally done, and also in cases where correct fall-through is missed by someone maintaining the code. This latter is a subtle addition to the bugs associated with fall-through, because even if your code is perfectly bug-free, your fall-through can still cause problems.

与上述最后两点相关的是,我们可以参考最新版《K&R》中的一段话:

从一种情况失败到另一种情况不是健壮的,当程序被修改时很容易解体。除了对单个计算使用多个标签外,应该谨慎使用并注释fall-贯穿。 作为一种良好的形式,在最后一个case(这里的默认值)后面加上一个break,即使这在逻辑上是不必要的。有一天,当最后添加了另一个案例时,这一点防御性编程将拯救您。

所以,从马的嘴,摔倒在C是有问题的。始终用注释记录错误被认为是一种很好的实践,这是一个普遍原则的应用,即应该记录在哪里做了不寻常的事情,因为这将在以后的代码检查中绊倒,并且/或使您的代码看起来像新手的错误,而实际上它是正确的。

想想看,代码是这样的:

switch(x)
{
  case 1:
   foo();
   /* FALLTHRU */
  case 2:
    bar();
    break;
}

是在代码中添加一些使fall-through显式的东西,它只是不能被编译器检测到(或其缺失可以被检测到)。

因此,在c#中必须显式地使用fall-through这一事实并不会给那些用其他C风格语言写得很好的人增加任何惩罚,因为他们已经在他们的fall-through中显式了。†

最后,在这里使用goto已经是C和其他类似语言的规范:

switch(x)
{
  case 0:
  case 1:
  case 2:
    foo();
    goto below_six;
  case 3:
    bar();
    goto below_six;
  case 4:
    baz();
    /* FALLTHRU */
  case 5:
  below_six:
    qux();
    break;
  default:
    quux();
}

In this sort of case where we want a block to be included in the code executed for a value other than just that which brings one to the preceding block, then we're already having to use goto. (Of course, there are means and ways of avoiding this with different conditionals but that's true of just about everything relating to this question). As such C# built on the already normal way to deal with one situation where we want to hit more than one block of code in a switch, and just generalised it to cover fall-through as well. It also made both cases more convenient and self-documenting, since we have to add a new label in C but can use the case as a label in C#. In C# we can get rid of the below_six label and use goto case 5 which is clearer as to what we are doing. (We'd also have to add break for the default, which I left out just to make the above C code clearly not C# code).

总之:

C# no longer relates to unoptimised compiler output as directly as C code did 40 years ago (nor does C these days), which makes one of the inspirations of fall-through irrelevant. C# remains compatible with C in not just having implicit break, for easier learning of the language by those familiar with similar languages, and easier porting. C# removes a possible source of bugs or misunderstood code that has been well-documented as causing problems for the last four decades. C# makes existing best-practice with C (document fall through) enforceable by the compiler. C# makes the unusual case the one with more explicit code, the usual case the one with the code one just writes automatically. C# uses the same goto-based approach for hitting the same block from different case labels as is used in C. It just generalises it to some other cases. C# makes that goto-based approach more convenient, and clearer, than it is in C, by allowing case statements to act as labels.

总而言之,这是一个非常合理的设计决策


*Some forms of BASIC would allow one to do the likes of GOTO (x AND 7) * 50 + 240 which while brittle and hence a particularly persuasive case for banning goto, does serve to show a higher-language equivalent of the sort of way that lower-level code can make a jump based on arithmetic upon a value, which is much more reasonable when it's the result of compilation rather than something that has to be maintained manually. Implementations of Duff's Device in particular lend themselves well to the equivalent machine code or IL because each block of instructions will often be the same length without needing the addition of nop fillers.

†达夫的装置再次出现在这里,作为一个合理的例外。事实上,在这种模式和类似的模式下,操作的重复使得fall-through的使用相对清晰,即使没有明确的注释。


只是一个简短的说明,Xamarin的编译器实际上犯了这个错误,它允许fallthrough。这个问题应该已经解决了,但还没有发布。在一些代码中发现了这一点,而编译器并没有抱怨。


switch (c#参考)说

c#要求开关部分的结尾,包括最后一个,

所以你还需要添加一个休息;到默认的部分,否则仍然会有编译器错误。