我已经环顾了一下但是却无法找到新的C#6.0编译器如何分解新的null传播命令的答案,如下所示:
BaseType myObj = new DerivedType(); string myString = (myObj as DerivedType)?.DerivedSpecificProperty;
我想知道的是它究竟是如何处理这个问题的.
它是否将ascast缓存到一个新的DerivedType变量中(也就是说,这只是一个ascast的语法糖,然后是一个null比较).
或者,如果它实际上是强制转换,请检查null,如果不为null,则重新运行并继续运行.
解决方法
Does it cache the
as
cast into a newDerivedType
variable (i.e.,this is just syntactic sugar for anas
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变量.引用只是存储在堆栈中).