考虑以下代码
public bool GetFalse()
{
return false;
}
public bool GetTrue()
{
return true;
}
Run Code Online (Sandbox Code Playgroud)
如何强制此表达式GetFalse() && GetTrue()执行第二个方法?
你不能因为逻辑AND运算符短路.在一般情况下,尽管存在完全有效的用途(即,if( someObj != null && someObj.Value == whatever )你可以使用&不会短路的按位和运算符(),但是我不会这样做,因此避免像这样的表达式产生副作用是个好主意.去做.
您应该首先将这两个方法调用拆分为变量,然后执行检查是否需要执行它们.
bool first = SomeMethodCall();
bool second = SomeMethodThatMustExecute();
if( first && second )
{
// ...
}
Run Code Online (Sandbox Code Playgroud)