在 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/