如果一个且只有一个参数为真,则返回运算符

时间:2016-06-10 22:07:53

标签: c# operators

我在C#中创建一个if语句,如果只有一个参数为true,我想返回true。我将在示例中使用||,因为这是我能想到的最接近的事情:

int a = 1;
int b = 2;
int c = 3;

if(a == 1 || b == 2)
{
Console.Log("The first statement is true")
}

if(a == 1 || b == 3)
{
Console.Log("The second statement is true")
}

if(a == 0 || b == 0 || c == 3)
{
Console.Log("The third statement is true")
}

if(a == 1 || b == 0 || c == 3)
{
Console.Log("The fourth statement is true")
}

//Output:
//The second statement is true
//The third statement is true

再次,将||视为我正在寻找的运营商。这样的运算符是否存在,或者我应该定义自己的布尔函数吗?

3 个答案:

答案 0 :(得分:5)

对于两个表达式,您可以使用XOR:

if (a == 1 ^ b == 0)

对于两个以上,您可以执行以下操作:

if (new[] { a == 1, b == 0, c == 2 }.Count(x => x) == 1)

这基本上算上所有" true"从表达式构造的数组元素,并检查计数是否为1。

不可否认,首先评估所有条件,并且即使前两个条件为真,也将计算所有条件(因此最后一个条件无关紧要)。如果这对你来说最终会变得昂贵,那么还有更复杂的选择,但除非它确实存在问题,否则我肯定会坚持这样的事情。

答案 1 :(得分:0)

没有这样的操作员。但是你可以试试这个:

var statements = new[] { a == 0, b == 2, c == 2 };
switch (statements.Count(x => x))
{
    case 0: Console.WriteLine("None of statement is true"); break;
    case 1:
        Console.WriteLine("The {0} statement is true", 
            new[] { "first", "second", "third" }.Skip(statements.TakeWhile(x => !x).Count()).First());
        break;

    default:
        Console.WriteLine("More than one statement is true");
        break;
}

输出:

  

第二个陈述是真的

答案 2 :(得分:0)

对于2个操作数,XOR(^)运算符将执行此操作。来自MSDN

  

对于 bool 操作数,^计算逻辑异或 -   操作数;也就是说,结果是 true 当且仅当恰好其中之一   它的操作数是 true

对于三个或更多运算符Jon is correct,您只需循环遍历条件。但是,如果要检查非常多的条件(或者只是一些非常昂贵的条件),那么当找到第二个true时,可能会通过短路结果来提高性能。 ,像这样:

var conditions = ...
if (conditions.Where(x => x).Take(2).Count() == 1) 

或者如果你喜欢不那么神秘的东西,也许是一种延伸方法

public static bool ExactlyOne(this IEnumerable<T> source, Func<T, bool> predicate)
{
    var found = false;
    foreach(var x in source)
    {
        var result = predicate(x);
        if (result && found) {
            return false;
        }
        found = result;
    }

    return found;
}

var conditions = ...
if (conditions.ExactlyOne(x => x)) 
相关问题