转到C#的困难

c00*_*0fd 1 c# goto

为什么我会收到以下编译器错误:

//错误CS0159:没有这样的标签'lbl_proc_20'

使用以下代码:

//JUST A DUMMY CODE TO ILLUSTRATE THE CONCEPT
int a = resultOfFunction1();
int b = resultOfFunction2();

//10+ Local variables that are calculated depending on the results above

if (a < 10)
{
    switch (b)
    {
        case 0:
            //Actions for A<10, B=0, using local variables
            break;
        case 1:
            double c = someFunction(a, b);  //In real code involves calculations based on a and b
            if(c > 10.0)
                goto lbl_proc_20;   //error CS0159: No such label 'lbl_proc_20' within the scope of the goto statement

                    //Actions for A<10, B=1, using local variables
            break;
        default:
            //Actions for A<10, B=Other, using local variables
            break;
    }
}
else if (a < 20)
{
lbl_proc_20:
    switch(b)
    {
        case 0:
            //Actions for A<20, B=0, using local variables
            break;
        case 1:
            //Actions for A<20, B=1, using local variables
            break;
        case 2:
            //Actions for A<20, B=2, using local variables
            break;
        default:
            //Actions for A<20, B=Other, using local variables
            break;
    }
}
else if (a < 30)
{
    switch(b)
    {
        case 0:
            //Actions for A<30, B=0, using local variables
            break;
        case 1:
            //Actions for A<30, B=1, using local variables
            break;
        case 2:
            //Actions for A<30, B=2, using local variables
            break;
        default:
            //Actions for A<30, B=Other, using local variables
            break;
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么我收到goto语句的错误以及如何使其工作?

编辑:更改了示例以说明实际代码.

Chr*_*nte 10

您只能用于goto跳转到范围内的标签goto.来自描述错误的文档CS0159:

无法在goto语句的范围内找到goto语句引用的标签.

虽然标签存在,但您不能跳出if块到else块中.其中的代码else与包含该代码的代码的范围不同goto.

是时候重构您的代码,因此它不需要goto.

编辑

你应该尝试简化你的逻辑.多个函数比goto语句更好.

您可能需要考虑的一个选项是Windows Workflow Foundation.它是一个非常简洁的工具,可以让您在视觉上将您的逻辑表示为流程图.然后,WWF将生成处理您指定的逻辑所需的代码.这可能有用,因为它看起来像是在创建某种类型的有限状态机或类似的过程.

  • @ user843732:不知道你的代码实际应该做什么. (4认同)