运算符 && 的问题
考虑以下代码
public bool GetFalse()
{
return false;
}
public bool GetTrue()
{
return true;
}
如何强制此表达式 GetFalse() && GetTrue()
执行第二个方法?
Considering the following code
public bool GetFalse()
{
return false;
}
public bool GetTrue()
{
return true;
}
How can I force this expression GetFalse() && GetTrue()
to execute second Method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试使用:
Try with:
不能,因为逻辑 AND 运算符短路。在一般情况下,避免此类表达式的副作用是一个好主意,尽管存在完全有效的用途(即
if( someObj != null && someObj.Value == another )
。您可以使用不会短路的按位与运算符(&
),但我不会这样做,您应该首先将这两个方法调用拆分为变量,然后执行。检查您是否需要它们 执行。
You can't because the logical AND operator short circuits. In the general case it is a good idea to avoid side effects from expressions like that, although there are perfectly valid uses (i.e.,
if( someObj != null && someObj.Value == whatever )
. You could use the bitwise and operator (&
) which does not short circuit, but again, I wouldn't do that.You should split those two method calls into variables first and then perform the check if you need them both to execute.
使用非短路版本(在不使用布尔值时也称为按位 AND):
Use the non-short circuiting version (also known as the bit-wise AND when not working with Boolean values):
这是一个优化问题。由于表达式中调用的第一个方法为 false,整个表达式不可能为 true,因此不会调用表达式中的第二个方法。如果有必要调用它来产生副作用(依赖副作用是不好的做法,但是YMMV),应该使用这样的东西:
This is an optimization issue. Since the first method called in the expression is false, the entire expression cannot be true, so the second method in the expression is not called. If it is necessary to call this for a side effect (bad practice to rely on a side effect, but YMMV), something like this should be used:
假设您的实际函数执行一些特定任务并返回一个指示(例如)成功或失败的值,我更愿意将其写为
然后您可以使用 fooResult && barResult 在您的代码中。
Assuming that your actual functions perform some specific tasks and return a value indicating (for example) success or failure I would prefer to see this written as
And then you can use
fooResult && barResult
in your code.