c# 支持在 if 语句中链接 && 还是它们必须嵌套?

Does c# support chaining && in an if statement or do they have to be nested?

如果我使用下面的代码,

if (obj.ContactDetail != null && obj.ContactDetail.Id != Guid.Empty)

我会在后半部分 (.Id) 出现空引用错误,还是会表现得像 javascript 并且在比较的前半部分脱离 If。

我知道已经回答了这个问题,但我不知道用于查找它的条款。对不起

这叫做短路求值,是的,&& 是一个运算符,如果第一个条件还没有 false

则只对第二个条件求值

MSDN:

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

The operation x && y corresponds to the operation x & y except that if x is false, y is not evaluated, because the result of the AND operation is false no matter what the value of y is. This is known as "short-circuit" evaluation. The conditional-AND operator cannot be overloaded, but overloads of the regular logical operators and operators true and false are, with certain restrictions, also considered overloads of the conditional logical operators.

不,如果第一部分 obj.ContactDetail != null 的计算结果为 false,那么您将不会得到 NRE,那么它根本不会对第二部分进行计算。只有当第一部分的计算结果为 TRUE 时,才会计算第二部分。