空传播运算符

Null propagation operator

我环顾四周,但未能找到新的 C# 6.0 编译器如何分解新的空传播命令的答案,例如:

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

我想知道它是如何处理这个的。

它是否将 as 转换缓存到新的 DerivedType 变量中(即,这只是 as 转换后跟空比较的语法糖)。

或者如果它确实 as 投射它,检查是否为 null,如果不是 null,则重新投射并继续。

Does it cache the as cast into a new DerivedType variable (i.e., this is just syntactic sugar for an as cast followed by an null comparison).

是的。

你的代码将被编译成这样:

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

你可以看到 this TryRoslyn example (尽管,正如 hvd 评论的那样,通过查看 IL 你可以看到实际上没有 DerivedType 变量。引用只是存储在堆栈)。