我正在努力完成这个 if 语句。必须有一种更简单的方法来完成所有组合,因为这不是好的做法。
if( one == true && two == true && three == true ...)
else if( one != true && two == true && three == true ...)
我想知道我是否想遍历所有组合是否有任何其他方法可以做到这一点而不是复制表达式?
最佳答案
一种方法是将您的 one
、two
和 three
值转换为单个 int
正确设置位,并在二进制掩码上使用 switch
语句,如下所示:
int combined=0;
// Construct a binary representation using your Boolean values as bits:
// Value of one goes to bit zero
if (one) combined |= (1 << 0);
// Value of one goes to bit one
if (two) combined |= (1 << 1);
// Value of three goes to bit two
if (three) combined |= (1 << 2);
switch (combined) {
case 0: // All false
break;
case 1: // one is true, other are all false
break;
...
case 7: // All true
break;
}
所有八个组合现在都编码为整数值:
int three two one
_-- ----- --- ---
0 - 0 0 0
1 - 0 0 1
2 - 0 1 0
3 - 0 1 1
4 - 1 0 0
5 - 1 0 1
6 - 1 1 0
7 - 1 1 1
不用说,对于没有记住小数的二进制表示的代码读者,您需要对这样的代码进行大量注释。
关于c# - 多个场景的if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26347287/