is there a equivalent of Java's labelled break in C# or a workaround

无人久伴 提交于 2019-11-30 00:24:04

问题


I am converting some Java code to C# and have found a few labelled "break" statements (e.g.)

label1:
    while (somethingA) {
       ...
        while (somethingB) {
            if (condition) {
                break label1;
            }
        }
     }

Is there an equivalent in C# (current reading suggests not) and if not is there any conversion other than (say) having bool flags to indicate whether to break at each loop end (e.g.)

bool label1 = false;
while (somethingA)
{
   ...
    while (somethingB)
    {
        if (condition)
        {
            label1 = true;
            break;
        }
    }
    if (label1)
    {
        break;
    }
}
// breaks to here

I'd be interested as to why C# doesn't have this as it doesn't seem to be very evil.


回答1:


You can just use goto to jump directly to a label.

while (somethingA)
{
    // ...
    while (somethingB)
    {
        if (condition)
        {
            goto label1;
        }
    }
}
label1:
   // ...

In C-like languages, goto often ends up cleaner for breaking nested loops, as opposed to keeping track of boolean variables and repeatedly checking them at the end of each loop.



来源:https://stackoverflow.com/questions/1548154/is-there-a-equivalent-of-javas-labelled-break-in-c-sharp-or-a-workaround

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!