如何退出 C# 中的 foreach 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/456276/
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
How do I exit a foreach loop in C#?
提问by
foreach (var name in parent.names)
{
if name.lastname == null)
{
Violated = true;
this.message = "lastname reqd";
}
if (!Violated)
{
Violated = !(name.firstname == null) ? false : true;
if (ruleViolated)
this.message = "firstname reqd";
}
}
Whenever violated is true, I want to get out of the foreach
loop immediately. How do I do it?
每当违反是真的,我想foreach
立即跳出循环。我该怎么做?
回答by configurator
Use break
.
使用break
.
Unrelated to your question, I see in your code the line:
与您的问题无关,我在您的代码中看到了这一行:
Violated = !(name.firstname == null) ? false : true;
In this line, you take a boolean value (name.firstname == null)
. Then, you apply the !
operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null)
. Why not use that, as in:
在这一行中,您使用一个布尔值(name.firstname == null)
。然后,您将!
运算符应用于它。然后,如果值为 true,则将 Violated 设置为 false;否则为真。所以基本上, Violated 被设置为与原始表达式相同的值(name.firstname == null)
。为什么不使用它,如:
Violated = (name.firstname == null);
回答by Greg Beech
Just use the statement:
只需使用以下语句:
break;
回答by Marcelo Lujan
Look at this code, it can help you to get out of the loop fast!
看看这段代码,它可以帮助你快速跳出循环!
foreach (var name in parent.names)
{
if (name.lastname == null)
{
Violated = true;
this.message = "lastname reqd";
break;
}
else if (name.firstname == null)
{
Violated = true;
this.message = "firstname reqd";
break;
}
}
回答by Sharunas Bielskis
During testing I found that foreach loop after break go to the loop beging and not out of the loop. So I changed foreach into for and break in this case work correctly- after break program flow goes out of the loop.
在测试期间,我发现 break 之后的 foreach 循环进入循环开始而不是循环之外。因此,我将 foreach 更改为 for 并在这种情况下 break 正常工作 - 在 break 程序流程退出循环之后。