C#吗?操作员短路?
在C#中使用??
运算符时,如果要测试的值不为null会短路吗?
When using the ??
operator in C#, does it short circuit if the value being tested is not null?
示例:
string test = null;
string test2 = test ?? "Default";
string test3 = test2 ?? test.ToLower();
test3行成功还是抛出空引用异常?
Does the test3 line succeed or throw a null reference exception?
以另一种方式表达问题的方式是:右手表达??吗?如果左手不为空,运算符会得到评估吗?
So another way to phrase the question: Will the right hand expression of the ?? operator get evaluated if the left hand is not null?
Yes, it says so in the C# Language Specification (highlighting by me):
a ?? b
形式的空合并表达式要求a
为可空类型或引用类型.如果a
不为空,则a ?? b
的结果为a
;否则,结果为b
. 仅当a
为空时,该操作才会评估b
.
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.