未来访客请注意:这个问题是基于错误的重现代码。这?.
操作员确实短路了。您现在可以关闭此浏览器选项卡。
网络上有许多来源声称空条件运算符 (?.
)短路(例如http://www.informit.com/articles/article.aspx?p=2421572 http://www.informit.com/articles/article.aspx?p=2421572,搜索“电路”)。我无法检测到任何这样的事情:
static void Main()
{
var c = new C();
Console.WriteLine(c?.Inner?.Inner); //does not rely on short circuiting, works
Console.WriteLine(c?.Inner.Inner); //throws NullReferenceException
}
class C
{
public C Inner;
}
在这里,第一行有效因为第二个?.
。第二?.
将 null 视为其第一个操作数,因此也返回 null。这不是短路。
显然,即使触发了 null 情况,链的其余部分也会执行。链不会中止。对我来说,短路意味着链条中止。MSDN 声称情况确实如此 https://msdn.microsoft.com/en-us/library/dn986595.aspx但代码示例没有演示短路:
//The last example demonstrates that the null-condition operators are short-circuiting
int? count = customers?[0]?.Orders?.Count();
// null if customers, the first customer, or Orders is null
在 C# 6 开发周期中此行为是否发生过变化?这可以解释网络上的不良来源。如果短路根本不存在,为什么还有那么多关于短路的讨论呢?我可能在这里误解了一些东西。
This https://stackoverflow.com/questions/30765145/does-c-sharp-6-elvis-operator-null-propagation-short-circuit不是重复的,因为它与操作员是否短路有关(答案:否,尽管接受的答案没有这么说)。这位候选人 https://stackoverflow.com/questions/25666993/c-sharp-null-propagating-operator-conditional-access-expression-if-blocks是关于可空布尔值和其他不相关的。