开关盒中的额外条件(Fallthrough?)

时间:2018-11-28 13:23:42

标签: c#

我需要在C#的切换案例中使用额外的条件。假设我们有几个案例需要做Stuff A和B,但是案例4需要Stuff C + Stuff Extra:

public void myFunction(int value)
{
    switch(value)
    {
        case 0:
            //Stuff A
            break;

        case 1:
            //Stuff B
            break;

        case 2:
        case 3:
        case 4:
            //Stuff C

            //Am I forced to use an If to a special condition of case 4?
            if(value == 4)
            {
                //Extra stuff for case 4
            }
            break;  
    }
}

是否有另一种无需使用If语句的方式?

2 个答案:

答案 0 :(得分:2)

我尝试了goto解决方案,它确实有效。谢谢您的回答:

 public void myFunction(int value)
        {
            switch (value)
            {
               case 0:
                     //Stuff A
                     break;

case 1: //Stuff B break; case 2: case 3: //Stuff C break; case 4: //Requires "Extra stuff" and "Stuff C" //Extra stuff for case 4 goto case 3; //another possible cases... case 5: //etc break; } }

请注意,此解决方案仅在执行语句时不需要具体顺序的情况下才有效。

例如,在这种情况下,如果必须在“ Stuff C”之后执行“多余的东西”,则正确的方法是在情况3中使用If语句。

答案 1 :(得分:0)

这里有点奇怪,将本地功能与switch结合在一起:

请勿建议编写以下代码:

void Main()
{
    int value = 4;
    switch (value)
    {
        case 0:
            //Stuff A
            break;


        case 1:
            //Stuff B
            break;

        case 2:
        case 3:
            common234(); void common234()
            {
                Console.WriteLine("2-4");
            }
            break;

        case 4:
            common234();
            Console.WriteLine("only 4");
            break;

        //another possible cases...
        case 5:
            //etc 
            break;
    }
}