为什么 IF 语句遍历所有 AND 条件,即使第一个为假
Why IF statement iterate over all AND conditions even if the first is false
在 C# 中,我有一个像这样的 IF 条件
if(x != null && x.myprop != "value")
{
//
}
当 x 为 null 时,为什么编译器在“&&”运算符之后继续,即使保证不满足条件。
如果我在 x 为 null 时 x.myprop 我有 null 异常,我知道 '?'解决问题,但我不明白为什么它会继续。
抱歉我的英语不好。
你解释的是不可能的。 null pointer
异常可能发生在代码的另一部分。在 C#
中,依靠短路(这就是您所描述的)完全没问题。
规格说明:
The && and || operators are called the conditional logical operators.
They are also called the “shortcircuiting” logical operators. ... The
operation x && y corresponds to the operation x & y, except that y is
evaluated only if x is true ... The operation x && y is evaluated as
(bool)x ? (bool)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.
&& operator in C# short circuits 所以你不可能看到这种行为。
The conditional-AND operator (&&) performs a logical-AND of its bool
operands, but only evaluates its second operand if necessary.
但是,您确定您没有错误地使用 & 运算符(which does not short circuit)吗?
The binary & operator evaluates both operators regardless of the first
one's value, in contrast to the conditional AND operator &&.
在 C# 中,我有一个像这样的 IF 条件
if(x != null && x.myprop != "value")
{
//
}
当 x 为 null 时,为什么编译器在“&&”运算符之后继续,即使保证不满足条件。
如果我在 x 为 null 时 x.myprop 我有 null 异常,我知道 '?'解决问题,但我不明白为什么它会继续。 抱歉我的英语不好。
你解释的是不可能的。 null pointer
异常可能发生在代码的另一部分。在 C#
中,依靠短路(这就是您所描述的)完全没问题。
规格说明:
The && and || operators are called the conditional logical operators. They are also called the “shortcircuiting” logical operators. ... The operation x && y corresponds to the operation x & y, except that y is evaluated only if x is true ... The operation x && y is evaluated as (bool)x ? (bool)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.
&& operator in C# short circuits 所以你不可能看到这种行为。
The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.
但是,您确定您没有错误地使用 & 运算符(which does not short circuit)吗?
The binary & operator evaluates both operators regardless of the first one's value, in contrast to the conditional AND operator &&.