假设我有三个条件,由布尔变量表示。如何使以下代码块更简单?
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
可以删除吗?感谢。
答案 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
}
如果condition1
和condition2
为真(但不是条件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
}