优化嵌套的If语句和条件

时间:2017-07-19 07:21:13

标签: c# if-statement boolean

假设我有三个条件,由布尔变量表示。如何使以下代码块更简单?

bool condition1, condition2, condition3; //assuming they already have values

if (condition1 && condition2)
{
    if (condition3)
    {
        //Few lines of code here
    }
}
else
{
    //Same few lines of code above here
}

除了放置代码行之外,还有更好/更简洁的方法来简化这个问题吗?在一个方法?内部if可以删除吗?感谢。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

if (!(condition1 && condition2) || (condition1 && condition2 && condition3))
{
     //Few lines of code here
}

或者在condition1 && condition2语句之前等同if以使代码更简单:

bool c12 = condition1 && condition2;

if (!c12 || (c12 && condition3))
{
     //Few lines of code here
}

如果condition1condition2为真(但不是条件3),则需要执行其他操作:

bool c12 = condition1 && condition2;

if (!c12 || (c12 && condition3))
{
     if(c12 && !condition3)
     {
         // Do extra stuff
     }

     //Few lines of code here
}

答案 1 :(得分:-1)

我认为这是相同且较小的代码:

if (condition1 && condition2 && condition3)
{
        //Few lines of code here
}
else
{
    //Same few lines of code above here
}