如果声明多个场景

时间:2014-10-13 19:16:16

标签: c#

我正在努力完成这个if语句。必须有一种更简单的方法来完成所有组合,因为这不是一种好的做法。

if( one == true && two == true && three == true ...)
else if( one != true && two == true && three == true ...)

我想知道我是否想要通过所有组合是否有其他方法可以做到这一点而不是复制表达式?

5 个答案:

答案 0 :(得分:19)

一种方法是将onetwothree值转换为单个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 

毋庸置疑,您需要为那些没有记忆小数字二进制表示的代码读者大量注释这样的代码。

答案 1 :(得分:18)

可以做类似的事情:

int i = (one ? 1 : 0) | (two ? 2 : 0) | (three ? 4 : 0);

switch(i)
{
     case 0:
         // ...
     case 1:
         // ...
     case 7:
         // ...
}

这将非常快 - 它将是一个直接跳转(the switch opcode),并且表达式只会被评估一次。

答案 2 :(得分:1)

你不需要one != true在第二行,因为你已经消除了所有情况都属实的情况。您可以使用它简化:

if (one && two && three) {
}
else if (one && two) { 
} 
else if (two && three) {
}
else if (one && three) {
}
else if (one) {
}
else if (two) {
}
else if (three) {
}
else
{
  // none true
} 

答案 3 :(得分:0)

也许你可以试试这个:

if (one && two && three)
{
    // Do something
}
else if(one && two && three ...)
{
    // Do Something else
}

检查虚假陈述使用&#39;!&#39;:

if (!one && two ...)

答案 4 :(得分:-1)

执行此操作的最佳方法是将每个项目声明为bool。这样,您可以消除所有== ?行,并具有以下内容:

bool one = true; // Random decision to call it true, just for testing
bool two = false;
bool three = true;

if(one && two && three)
    // Do something
else if(!one && two && three)
    // Do something else.