C#中如何一次性跳出多个循环?
如果我有嵌套循环,并且我想立即打破所有嵌套循环怎么办?
while (true) {
// ...
while (shouldCont) {
// ...
while (shouldGo) {
// ...
if (timeToStop) {
break; // Break out of everything?
}
}
}
}
在 PHP 中,break
采用一个参数来表示要中断的循环数。 C# 中可以完成这样的事情吗?
一些可怕的东西怎么样,比如goto
?
// In the innermost loop
goto BREAK
// ...
BREAK: break; break; break;
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, break
takes an argument for the number of loops to break out of. Can something like this be done in C#?
What about something hideous, like goto
?
// In the innermost loop
goto BREAK
// ...
BREAK: break; break; break;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将嵌套循环提取到函数中,然后您可以使用 return 从任何地方退出循环,而不是break。
Extract your nested loops into a function and then you can use return to get out of the loop from anywhere, rather than break.
引入另一个控制标志并将其放入所有嵌套的 while 条件中,如下所示。还用它替换 while(true) 条件
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
后藤只有在受到虐待时才会变得丑陋。退出某些嵌套的最内层循环是可以接受的。但是……人们首先要问为什么那里有这么多筑巢的地方。
简短回答:不。
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.
如果您想打破整个方法,请使用下面的代码。
如果您只想打破方法内的一系列循环而不打破该方法,那么已经发布的答案之一就可以完成这项工作。
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.
您只需使用
goto
即可跳出循环:You can just use
goto
to get out of the loops: