为什么在 C# 中通过 Switch 案例编译

Why do fall through Switch cases compile in c#

众所周知,c# 中的 switch cases 不允许您根据 MSDN

Execution of the statement list in the selected switch section begins with the first statement and proceeds through the statement list, typically until a jump statement, such as a break, goto case, return, or throw, is reached. At that point, control is transferred outside the switch statement or to another case label.

Unlike C++, C# does not allow execution to continue from one switch section to the next. The following code causes an error.

如果是这样,为什么编译:

void Main()
{
    int  s = 3;
    switch (s)
    {
        case 1:
        case 2:
        case 3:
            Console.WriteLine("hit 3");
            break;
    }
}

这不应该被识别为编译时错误吗?

首先,您提供的代码不会引发 运行 时间错误。其次,它属于不同的类别(来自同一篇 MSDN 文章,重点是我的):

A switch statement can include any number of switch sections, and each section can have one or more case labels (as shown in the string case labels example below). However, no two case labels may contain the same constant value.

不同之处在于您是否有多个空 case 语句,这是允许的。但是你不能有一个 case 里面有代码,让它失败。