首页 > 解决方案 > If 语句内 If 语句条件

问题描述

我有这个代码:

int a, b;

if (a > 0)
{
    a--;
    DoSomething()
}
else if (b > 0)
{
    b--;
    DoSomething();
}

我听说最好不要DoSomething();两次写同一行(),所以有没有办法做到这一点:

int a, b;

if (a > 0 /* if true a--; */ || b > 0 /* if true b--; */)
{
    DoSomething();
}

换句话说,有没有更好的方法来做到这一点(不写DoSomething();两次):

int a, b;

if (a > 0)
{
    a--;
    DoSomething()
}
else if (b > 0)
{
    b--;
    DoSomething();
}

标签: c#

解决方案


如果这些是方法中唯一或最后的语句,您可以在附加的 else 语句中返回:

if (a > 0)
{
    a--;
}
else if (b > 0)
{
    b--;
}
else
{
    return;
} 
DoSomething();

如果这些是循环中的最后一个语句,您可以使用continue而不是return. 在开关盒中,您可以使用break.


如果DoSomething涉及更复杂的事情,那么使用标志是合适的。否则调用DoSomething两次就好了。

bool isDecremented = false;
if (a > 0)
{
    a--;
    isDecremented = true;
}
else if (b > 0)
{
    b--;
    isDecremented = true;
}

if (isDecremented)
{
    // Do something more complex.
}

推荐阅读