如何在一个switch语句中合并两个case语句

时间:2014-01-30 19:59:21

标签: c# c++

switch(code)
{
    case 'A':
    case 'a':
         // to do 
    default:
         // to do 
}

有没有办法将两个“案例”陈述合并在一起?

3 个答案:

答案 0 :(得分:8)

您只需要break;作为当前代码:

switch (code)
{
    case 'A':
    case 'a':
        break;
    // to do 
    default:
        // to do 
        break;
}

但是如果您要比较大写和小写字符,那么您可以使用char.ToUpperInvariant然后仅为大写字符指定案例:

switch (char.ToUpperInvariant(code))
{
    case 'A':
        break;
    // to do 
    default:
        // to do 
        break;
}

答案 1 :(得分:0)

http://msdn.microsoft.com/en-us/library/06tc147t.aspx

class Program
{
    static void Main(string[] args)
    {
        int switchExpression = 3;
        switch (switchExpression)
        {
            // A switch section can have more than one case label. 
            case 0:
            case 1:
                Console.WriteLine("Case 0 or 1");
                // Most switch sections contain a jump statement, such as 
                // a break, goto, or return. The end of the statement list 
                // must be unreachable. 
                break;
            case 2:
                Console.WriteLine("Case 2");
                break;
                // The following line causes a warning.
                Console.WriteLine("Unreachable code");
            // 7 - 4 in the following line evaluates to 3. 
            case 7 - 4:
                Console.WriteLine("Case 3");
                break;
            // If the value of switchExpression is not 0, 1, 2, or 3, the 
            // default case is executed. 
            default:
                Console.WriteLine("Default case (optional)");
                // You cannot "fall through" any switch section, including
                // the last one. 
                break;
        }
    }
}

答案 2 :(得分:0)

Switch将评估所遇到的所有条件,直至达到breakdefault或最后结束括号。

即它会执行任何匹配的case语句,直到它达到其中一条指令。

将所有等同的cases分组,并在最后一个之后添加break以合并它们。

请注意,如果没有匹配项,则会落入default块。