简体   繁体   English

空传播算子

[英]Null propagation operator

I've looked around a bit but haven't been able to find an answer to how the new C# 6.0 compiler breaks down the new null propagation command for something such as the following: 我已经环顾了一下但是却无法找到新的C#6.0编译器如何分解新的null传播命令的答案,如下所示:

BaseType myObj = new DerivedType();
string myString = (myObj as DerivedType)?.DerivedSpecificProperty;

What I want to know is how exactly it handles this. 我想知道的是它究竟是如何处理这个问题的。

Does it cache the as cast into a new DerivedType variable (ie, this is just syntactical sugar for an as cast followed by an null comparison). 是否缓存as浇铸成一个新的DerivedType变量(即,这是一个只是语法糖as投后跟空比较)。

Or if it actually as cast it, check for null, then if not null, recast and keep going. 或者,如果它实际上as强制转换,请检查null,如果不为null,则重新运行并继续运行。

Does it cache the as cast into a new DerivedType variable (ie, this is just syntactic sugar for an as cast followed by an null comparison). 是否缓存as浇铸成一个新的DerivedType变量(即,这是一个只是语法糖as投后跟空比较)。

Yes. 是。

Your code will be compiled to something like this: 您的代码将编译为以下内容:

BaseType myObj = new DerivedType();
DerivedType temp = myObj as DerivedType;
string myString = temp != null ? temp.DerivedSpecificProperty : null;

You can see that with this TryRoslyn example (though, as hvd commented, by looking at the IL you can see there isn't actually a DerivedType variable. The reference is simply stored on the stack). 您可以通过此TryRoslyn示例看到(但是,正如hvd所评论的那样,通过查看IL,您可以看到实际上没有DerivedType变量。引用只是存储在堆栈中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM