"null-conditional operator" 是用词不当吗?
Is "null-conditional operator" a misnomer?
据我了解,子表达式必须始终在父表达式之前求值。
(a + b) / (c + d)
在上面的例子中,a + b
和 c + d
总是在除法之前求值。我的理解是,即使 a、b、c 和 d 都可以为 null,这也是正确的 ,并且这是真正的运算符的行为。
但是,假设 a
为 null 并且这些方法存在,如果我们写
(a?.Add(b))?.DivideBy(c?.Add(d))
none 的方法被执行,即使 b
、c
和 d
不为空。
将 ?.
称为运算符是否合适,还是该术语的混蛋?
根据 manual
?. and ?[] null-conditional Operators
Tests the value of the left-hand operand for null before performing a
member access (?.
) or index (?[]
) operation; returns null
if the
left-hand operand evaluates to null
.
(粗体 是我的)。在你的情况下
(a?.Add(b))?.DivideBy(c?.Add(d))
可以改写为
a // a is null
?.Add(b) // left is null? Yes; then propagate null - don't compute Add
?.DivideBy(c?.Add(d)) // left is null? Yes; then propagate null - don't exec DivideBy
据我了解,子表达式必须始终在父表达式之前求值。
(a + b) / (c + d)
在上面的例子中,a + b
和 c + d
总是在除法之前求值。我的理解是,即使 a、b、c 和 d 都可以为 null,这也是正确的 ,并且这是真正的运算符的行为。
但是,假设 a
为 null 并且这些方法存在,如果我们写
(a?.Add(b))?.DivideBy(c?.Add(d))
none 的方法被执行,即使 b
、c
和 d
不为空。
将 ?.
称为运算符是否合适,还是该术语的混蛋?
根据 manual
?. and ?[] null-conditional Operators
Tests the value of the left-hand operand for null before performing a member access (
?.
) or index (?[]
) operation; returnsnull
if the left-hand operand evaluates tonull
.
(粗体 是我的)。在你的情况下
(a?.Add(b))?.DivideBy(c?.Add(d))
可以改写为
a // a is null
?.Add(b) // left is null? Yes; then propagate null - don't compute Add
?.DivideBy(c?.Add(d)) // left is null? Yes; then propagate null - don't exec DivideBy