如果左操作数的?运营商不为空,不正确的操作得到评估? [英] If the left operand to the ?? operator is not null, does the right operand get evaluated?
问题描述
我期待在使用 ??
操作符(空合并运算符)在C#中。但在MSDN的文档是有限的。
I'm looking at using the ??
operator (null-coalescing operator) in C#. But the documentation at MSDN is limited.
我的问题:如果左边的操作数不为空,不正确的操作数不断得到评估
My question: If the left-hand operand is not null, does the right-hand operand ever get evaluated?
推荐答案
与以往一样,C#的规范去这样的事情最好的地方。
As ever, the C# specification is the best place to go for this sort of thing.
从 C#5规范(重点煤矿)第7.13:
From section 7.13 of the C# 5 specification (emphasis mine):
一个空合并的形式 A的前pression? b
要求 A
是一个可空类型或引用类型。如果的
是 A A
就是非空,结果? b A
;否则,其结果是 B
。 的操作先计算 B
仅 A
为空。
A null coalescing expression of the form
a ?? b
requiresa
to be of a nullable type or reference type. Ifa
is non-null, the result ofa ?? b
isa
; otherwise, the result isb
. The operation evaluatesb
only ifa
is null.
有在任何转换都围绕着更多的详细信息,以及准确的行为,但是这是给你的问题的主要观点。另外值得一提的是,空合并运算符是右结合的,所以 A? B 12 ç
被评为 A? (二?? C)
...这意味着它仅评估 C
如果的两个的在
和 B
是空的。
There are more details around when any conversions are performed, and the exact behaviour, but that's the main point given your question. It's also worth noting that the null-coalescing operator is right-associative, so a ?? b ?? c
is evaluated as a ?? (b ?? c)
... which means it will only evaluate c
if both a
and b
are null.
这篇关于如果左操作数的?运营商不为空,不正确的操作得到评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!