在C#中使用??
运算符时,如果被测试的值不为null,是否会短路?
例子:
string test = null;
string test2 = test ?? "Default";
string test3 = test2 ?? test.ToLower();
test3行是成功还是抛出空引用异常?
那么问题的另一种表达方式:右 watch 达 ??如果左手不为空,运算符得到评估?
最佳答案
是的,它在 C# Language Specification 中这样说(由我突出显示):
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.
关于c# - c# 吗??运算符(operator)短路?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5318912/