Elegantly determine if more than one boolean is “true”

前端 未结 22 1131
深忆病人
深忆病人 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:37

    I'd write a function to receive any number of boolean values. It would return the number of those values that are true. Check the result for the number of values you need to be positive to do something.

    Work harder to make it clear, not clever!

    private int CountTrues( params bool[] booleans )
    {
        int result = 0;
        foreach ( bool b in booleans )
        {
            if ( b ) result++;
        }
    
        return result;
    }
    

提交回复
热议问题