gpt4 book ai didi

c# - "if (a() && b != null)""a()"会一直被评估吗?

转载 作者:IT王子 更新时间:2023-10-29 03:51:20 27 4
gpt4 key购买 nike

我有这样的代码:

if (a() && b != null) {
b.doSomething();
}

我需要 a() 的副作用,即使 bnull。它由 C# 保证吗?或者,如果 bnull,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 type bool [...] the operation is processed as follows:

  • The operation x && y is evaluated as x ? y : false. In other words, x is first evaluated and converted to type bool. Then, if x 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com