如何退出 C# 中的 foreach 循环? [英] How do I exit a foreach loop in C#?

查看:429
本文介绍了如何退出 C# 中的 foreach 循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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";
    }
}

只要有违反,我就想立即退出 foreach 循环.我该怎么做?

Whenever violated is true, I want to get out of the foreach loop immediately. How do I do it?

推荐答案

使用 break.

与您的问题无关,我在您的代码中看到了这一行:

Unrelated to your question, I see in your code the line:

Violated = !(name.firstname == null) ? false : true;

在这一行中,您使用一个布尔值 (name.firstname == null).然后,对它应用 ! 运算符.然后,如果值为 true,则将 Violated 设置为 false;否则为真.所以基本上, Violated 被设置为与原始表达式 (name.firstname == null) 相同的值.为什么不使用它,如:

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:

Violated = (name.firstname == null);

这篇关于如何退出 C# 中的 foreach 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆