c# - If 语句 - 'or' 但不是 'and'

标签 c# if-statement

在 C Sharp 中,如何设置 if 语句来检查多个条件之一是否为真?它必须只是条件之一,如果零个或两个或多个为真,则 if 应该为假。

最佳答案

您可以编写辅助方法。这样做的好处是它会短路,只评估需要的数量,

public static bool IsExactlyOneTrue(IEnumerable<Func<bool>> conditions) {
    bool any = false;
    foreach (var condition in conditions) {
        bool result = condition();
        if (any && result) {
            return false;
        }
        any = any | result;
    }
    return any;
}

关于c# - If 语句 - 'or' 但不是 'and',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10745144/

相关文章:

c# - 如何在 C# 中的 List<Tuple<string,string>> 中搜索字符串

c# - 来自文本文件的数据表?

c# - 如何验证作为哈希值存储在数据库中的密码?

c++ - 按概率对 if...else if 语句进行排序的效果是什么?

c++ - "if (var)"使用数字转换而不是 bool 值

c# - ObservableCollection<MyType> 上的扩展方法,MyType : IEnumerable<MyType>

c# - WPF Applicationdeployment.isnetworkdeployed 总是返回 false

Python 是否可以将两个 if 和一个 else 语句放在一起?

java - 如何使用 Java 计算器进行单操作数数学运算?

javascript - 在 HTML 标记上切换类时更改 Swiper.JS 设置的设置(自动播放、效果、循环)