Elegantly determine if more than one boolean is “true”

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

    I would do something like this, using the params argument.

            public void YourFunction()
            {
                if(AtLeast2AreTrue(b1, b2, b3, b4, b5))
                {
                    // do stuff
                }
            }
    
            private bool AtLeast2AreTrue(params bool[] values)
            {
                int trueCount = 0;
                for(int index = 0; index < values.Length || trueCount >= 2; index++)
                {
                    if(values[index])
                        trueCount++;
                }
    
                return trueCount > 2;
    
            }
    

提交回复
热议问题