Elegantly determine if more than one boolean is “true”

前端 未结 22 1105
深忆病人
深忆病人 2020-12-04 13:40

I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would al

22条回答
  •  孤城傲影
    2020-12-04 14:45

    I was recently having this same issue, where I had three boolean values, which I needed to check that only 1 of them was true at a time. For this I used the xor operator as follows:

    bool a = true;
    bool b = true;
    bool c = false;
    
    if (a || b || c)
    {
        if (a ^ b ^ c){
            //Throw Error
        }
    }
    

    This code will throw an error as a and b are both true.

    For reference: http://www.dotnetperls.com/xor

    I have only just found the xor operator in C# if anyone knows of any pit falls of this strategy, please let me know.

提交回复
热议问题