c# - 如何通过速记 "if-else"结果打破循环?

标签 c# loops if-statement break shorthand

假设我在循环中有一个简写的 if-else 语句,就像在这种情况下一样:

for(...)
{
    a = b == c ? b : c;
    // More unnecessary code if the result was true.
}

我想通过条件的结果来打破循环:

for(...)
{
    a = b == c ? b break : c;
    // Now the unnecessary code is not executed.
}

我意识到我可以像这个例子一样以完整的方式输入它:

for(...)
{
    if( b == c )
    {
        a = b;
        break;
    }
    else
    {
        a = c;
    }
    // Now the unnecessary code is not executed.
}

但它太长了,我试图将所有中断条件都放在一行中,因为它们有几个。

最佳答案

您可以在不使用三元运算符的情况下使用缩短的语法,但您尝试做的事情是不可能的。如果 if 中有 break 语句,则也不需要 else

for (...)
{
    if (b == c) { a = b; break; }

    a = c;
    // More code if b does not equal c
}

关于c# - 如何通过速记 "if-else"结果打破循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15815718/

相关文章:

c# - 我的 Visual Studio 2019 WPF 应用程序在它应该是 exe 时将 dll 设置为输出

javascript - 为什么这段代码看起来是在 return 语句之后执行的?

jquery - 如何通过 jQuery if 语句编辑 CSS 类

javascript - 来自字符串语句的 if 语句

c# - Fluent NHibernate 或 NHibernate 用于具有复杂关系的复杂数据库

c# - Paypal SOAP API - 快速结账 - 错误 10002

c# - 在 Entity Framework 6.1.3 中调用 SaveChanges 时获取实体名称

java - 为什么每个循环都不起作用?

c - 打印此图案背后的逻辑

python - 为什么 if-else 表达式的第二个条件中的尾随逗号导致第一个条件被转换为元组