C# If语句条件中的If语句

C# If语句条件中的If语句,c#,C#,我有以下代码: 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

我有以下代码:

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();
两次):


您可以使用本地方法来避免重复:

void DecrementAndDoSomething(ref int i)
{
    i--;
    DoSomething();
}

if (a > 0) DecrementAndDoSomething(ref a);
else if (b > 0) DecrementAndDoSomething(ref b);

如果这些是方法中的唯一语句或最后一个语句,则可以在其他else语句中返回:

if(a>0)
{
a——;
}
如果(b>0),则为else
{
b--;
}
其他的
{
回来
} 
DoSomething();
如果这些是循环中的最后语句,则可以使用
continue
而不是
return
。在开关情况下,您可以使用
break


如果
DoSomething
涉及更复杂的内容,则使用标志是合适的。否则调用
DoSomething
两次就可以了

bool isDecremented=false;
如果(a>0)
{
a——;
isDecremented=真;
}
如果(b>0),则为else
{
b--;
isDecremented=真;
}
如果(减少)
{
//做一些更复杂的事情。
}

这样写怎么样

            if ((a > 0 && a-- > 0) || (b > 0 && b-- > 0))
               DoSomething();

你必须这样做,因为在一个例子中你在做
a--
而在另一个例子中
b--
@Haytam,如果
语句不相关,那么
中的内容是什么;必须重复调用
DoSomething()
的原因是
else if
也是有条件的。如果它是一个包罗万象的
else
语句,那么重构代码就很容易了——只需将
DoSomething()
调用移到
if/else
语句之外,而不管该语句的实际主体是什么。请您的问题包括问题的详细描述或您所关心的问题,要在
if()
语句条件中添加另一个
if()
语句的位置,以及它应该执行的操作。还要解释两次编写方法调用时需要考虑的问题。根据
a
b
的可能值,应该如何执行操作?@CoolBots我只想调用
DoSomething()
如果其中一个条件是真的,你的意思是
ref int
?另外,现在不是只有两个调用不同的函数吗?@CoolBots
ref
是正确的,但是每次调用的函数都不一样。
DecrementAndDoSomething(参考a)我的意思是OP的代码没有改进-现在有两个对包装器方法的调用,而不是两个调用
DoSomething()
;代码的意图完全不清楚。
int a, b;

if (a > 0 || b > 0)
{
 if(a > 0)
    a--;
 else
   b--;

 DoSomething();
}
            if ((a > 0 && a-- > 0) || (b > 0 && b-- > 0))
               DoSomething();