作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我有这样的代码:
if (a() && b != null) {
b.doSomething();
}
我需要 a()
的副作用,即使 b
是 null
。它由 C# 保证吗?或者,如果 b
为 null
,C# 可能会省略 a()
调用?
最佳答案
是的,a()
将始终被计算。
由于条件是从左到右计算的,a()
将始终被计算,但是 b != null
仅在 a( )
返回 true
。
这是为您提供的准确规范引用,来自 C# 语言规范 3.0 版。我的强调和省略。
7.11.1 Boolean conditional logical operators
When the operands of
&&
or||
are of typebool
[...] the operation is processed as follows:
- The operation
x && y
is evaluated asx ? y : false
. In other words,x
is first evaluated and converted to type bool. Then, ifx
is true, y is evaluated and converted to type bool, and this becomes the result of the operation. Otherwise, the result of the operation is false.
关于c# - "if (a() && b != null)""a()"会一直被评估吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8241449/
我是一名优秀的程序员,十分优秀!