如何在 C# 中一次跳出多个循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2339142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:33:47  来源:igfitidea点击:

How to break out of multiple loops at once in C#?

c#loopsgotobreak

提问by Nick Heiner

What if I have nested loops, and I want to break out of all of them at once?

如果我有嵌套循环,并且我想一次摆脱所有循环怎么办?

while (true) {
    // ...
    while (shouldCont) {
        // ...
        while (shouldGo) {
            // ...
            if (timeToStop) {
                break; // Break out of everything?
            }
        }
    }
}

In PHP, breaktakes an argument for the number of loops to break out of. Can something like this be done in C#?

在 PHP 中,break需要一个参数来表示要跳出的循环数。可以在 C# 中完成这样的事情吗?

What about something hideous, like goto?

什么可怕的东西,比如goto

// In the innermost loop
goto BREAK
// ...
BREAK: break; break; break;

采纳答案by Michael Anderson

Extract your nested loops into a function and then you can use return to get out of the loop from anywhere, rather than break.

将嵌套循环提取到一个函数中,然后您可以使用 return 从任何地方退出循环,而不是中断。

回答by Andrew

Goto is only hideous when abused. To drop out of the innermost loop of some nesting it's acceptable. BUT... one has to ask why there is so much nesting there in the first place.

后藤只有在被滥用时才可怕。退出某些嵌套的最内层循环是可以接受的。但是......首先要问为什么那里有这么多嵌套。

Short answer: No.

简短的回答:没有。

回答by Fadrian Sudaman

Introduce another control flag and put it in all your nested while condition like below. Also replaces the while(true) condition you have with that

引入另一个控制标志并将其放入所有嵌套的 while 条件中,如下所示。还用它替换了你拥有的 while(true) 条件

bool keepLooping = true;
while (keepLooping) {
    // ...
    while (shouldCont && keepLooping) {
        // ...
        while (shouldGo && keepLooping) {
            // ...
            if (timeToStop) { 
                keepLooping  = false;
                break; // break out of everything?
            }
        }  
    }
}

回答by tolu619

If you want to break out of an entire method, then use the code below. If you only want to break out of a series of loops within a method without breaking out of the method, then one of the answers that have already been posted will do the job.

如果您想突破整个方法,请使用下面的代码。如果您只想跳出一个方法中的一系列循环而不跳出该方法,那么已经发布的一个答案就可以完成这项工作。

if (TimeToStop)
{
   return;
}