开发者

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

开发者 https://www.devze.com 2022-12-08 00:56 出处:网络
I am converting some Java code to C# and have found a few labelled \"break\" statements (开发者_如何学JAVAe.g.)

I am converting some Java code to C# and have found a few labelled "break" statements (开发者_如何学JAVAe.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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消