在为一天的大部分时间挠头之后,我偶然发现了一个非常奇怪的问题,即使用 .NET Native(用于 Windows UWP 应用程序)编译的 .NET 代码。
以下代码在任何 .NET 运行时环境中都可以正常工作,包括 Mono、Xamarin 等:
public class ABC {}
// ...
var constr = typeof(ABC).GetTypeInfo().DeclaredConstructors.First();
var abc = (ABC) constr?.Invoke(new object[0]);
// abc now contains an instance of ABC
在具有 .NET Native 编译的 Windows UWP 上,代码会引发类型异常NotImplementedException
但是,当删除空传播运算符时,它可以在 .NET Native 上完美运行:
public class ABC {}
// ...
var constr = typeof(ABC).GetTypeInfo().DeclaredConstructors.First();
var abc1 = (ABC) constr.Invoke(new object[0]);
// abc1 now contains an instance of ABC
// the following line throws an exception on .NET Native
// but it works fine on any other .NET runtime
var abc2 = (ABC) constr?.Invoke(new object[0]);
堆栈跟踪中发生异常的行是:
at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
in f:\dd\ndp\fxcore\CoreRT\src\System.Private.Reflection\src\System\Reflection\ConstructorInfo.cs:line 41
这闻起来像是编译器或运行时中的错误。这里发生了什么?我错过了什么吗?