74 c#
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";
}
}
Run Code Online (Sandbox Code Playgroud)
只要违反是真的,我想foreach立即退出循环.我该怎么做?
con*_*tor 191
使用 break;
与您的问题无关,我在您的代码中看到以下行:
Violated = !(name.firstname == null) ? false : true;
Run Code Online (Sandbox Code Playgroud)
在这一行中,您将获取一个布尔值(name.firstname == null).然后,您将!运算符应用于它.然后,如果值为true,则将Violated设置为false; 否则为真.所以基本上,Violated设置为与原始表达式相同的值(name.firstname == null).为什么不使用它,如:
Violated = (name.firstname == null);
Run Code Online (Sandbox Code Playgroud)
小智 7
看看这段代码,它可以帮助你快速走出循环!
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
184793 次 |
| 最近记录: |