简体   繁体   English

您能以编程方式在交换案例中调用特定案例吗?

[英]Can you programmatically call upon a specific case in a switch-case?

I have a switch case that looks like this: 我有一个开关盒,看起来像这样:

switch ( class.Function() )
{

    case firstThing:
    {

    }
        break;
    case secondThing:
    {
     //call third thing
     }
     break;
    case thirdThing:
    {

     }
     break;

    }

Is there any way to call a specific case in C / Objective-C? 有什么方法可以在C / Objective-C中调用特定案例?

不知道您为什么要这样做,但是在您的示例中,如果仅在case secondThing末尾省去了break语句,用户将继续执行后续的case语句,直到遇到中断为止。

It seems what you're trying to implement is switch statement fall through. 看来您要实现的是switch语句失败。 By leaving out the break statement after case #2, you will execute whatever code is in case #3. 通过在情况#2之后省略break语句,您将执行情况#3中的任何代码。 This may be what you want. 这可能就是您想要的。

switch ( class.Function() )
{

    case firstThing:
    {

    }
        break;
    case secondThing:
    {
     //go to case 3
    }

    case thirdThing:
    {

    }
     break;

    }

In your particular example, you could use case fall through, but that is not a solution to your question in general, and if there is code specific to secondThing , it can lead to confusion and could be considered bad practice. 在您的特定示例中,您可能会遇到用例失败的情况,但这通常不能解决您的问题,并且如果存在secondThing特定的代码,则可能导致混乱,可能被视为不良做法。

switch ( class.Function() )
{
    case firstThing:
    {

    }
    break;

    case secondThing:
    case thirdThing:
    {

    }
    break;
}

If you simply implement the body of each case as a function, then that is perhaps the more general solution: 如果仅将每种情况的主体实现为一个函数,则可能是更通用的解决方案:

switch( class.Function() )
{
    case firstThing:  something();                     break;
    case secondThing: anotherThing(); oneMoreThing();  break;
    case thirdThing:  oneMoreThing();                  break;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM