``??`` 运算符是否使用短路?
C# 中的 ??
运算符在求值时是否使用短路?
var result = myObject ?? ExpressionWithSideEffects();
当myObject
为非空时,ExpressionWithSideEffects()
的结果不会被使用,但是ExpressionWithSideEffects()
会被完全跳过吗?
Does the ??
operator in C# use shortcircuiting when evaluating?
var result = myObject ?? ExpressionWithSideEffects();
When myObject
is non-null, the result of ExpressionWithSideEffects()
is not used, but will ExpressionWithSideEffects()
be skipped completely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,确实会短路。
以下是在 LinqPad 中测试的代码片段:
第一个合并工作时不会引发异常,而第二个合并会引发异常(格式字符串无效)。
Yes, it does short circuit.
Here's a snippet to test in LinqPad:
The first coalesce works without throwing an exception while the second one does throw (the format string is invalid).
是的,确实如此。一如既往,C# 语言规范是权威来源1。
来自 C# 3 规范第 7.12 节(v3 而不是 4,因为 v4 规范涉及动态细节,这些细节与此处并不真正相关):
第二、第三和第四个项目符号是相关的。
1 关于您碰巧使用的编译器是否是实际真相来源,需要进行一场哲学讨论...某种语言的真相是什么 >打算做什么或者它目前做什么?
Yes it does. As ever, the C# language specification is the definitive source1.
From the C# 3 spec, section 7.12 (v3 rather than 4, as the v4 spec goes into dynamic details which aren't really relevant here):
The second, third and fourth bullets are the relevant ones.
1 There's a philosophical discussion to be had about whether the compiler you happen to be using is the actual source of truth... is the truth about a language what it's meant to do or what it currently does?
这就是我们进行单元测试的原因。
这些不是最好的测试名称,但您明白了。它表明空合并运算符按预期短路。
This is why we have unit testing.
These aren't the best test names, but you get the idea. It shows that the null coalesce operator short circuits as expected.