为什么我可以在调用链中省略后续的空条件运算符? [英] Why can I omit the subsequent null-conditional operators in an invocation chain?

查看:58
本文介绍了为什么我可以在调用链中省略后续的空条件运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

IEnumerable<int> xx = null;
var tt = xx?.Where(x => x > 2).Select(x => x.ToString());

它将 null 分配给 tt .问题是:为什么它能正常工作?

It assigns null to tt. The question is: why does it work properly?

我认为我必须先使用?.,然后再选择as ?.其中(...)返回 null .此外,如果我将第二行分成两行:

I thought I must use ?. before Select as ?.Where(...) returns null. Besides, if I split the second line into two separate lines:

IEnumerable<int> xx = null;
var yy = xx?.Where(x => x > 2);
var zz = yy.Select(x => x.ToString());

第三行将出现 ArgumentNullException ,为 yy == null .

魔术是什么?:)
如果这是由于短路引起的,我从没想过它会像这样.

What's the magic? :)
If this is because of short-circuiting, I've never thought that it can act like this.

推荐答案

是的,这是由于短路引起的.从 MSDN参考:

Yes, this is due to short-circuiting. From the MSDN reference:

... [T]零条件运算符正在短路.如果条件成员访问和索引操作链中的一个操作返回null,则链中其余部分的执行将停止.

...[T]he null-condition operators are short-circuiting. If one operation in a chain of conditional member access and index operation returns null, then the rest of the chain’s execution stops.

第二个示例引发的原因是因为您有单独的未链接语句.短路不能应用于多个语句.

The reason your second example throws is because you have separate unchained statements. Short-circuiting cannot be applied across multiple statements.

这篇关于为什么我可以在调用链中省略后续的空条件运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆