Activator.CreateInstance(type)引发异常

Moa*_*nou 3 c# .net-native uwp windows-10-universal

实际上这是一个非常奇怪的异常,因为它只在我将项目构建为Release时发生,并且当我选择Debug时根本不会发生.在调试模式下,应用程序运行良好,以下代码运行良好.

这是我的扩展方法的代码:

public static T DeepClone<T>(this T source) where T : UIElement
{
   T result;

   // Get the type
   Type type = source.GetType();

   // Create an instance
   result = Activator.CreateInstance(type) as T; //throws exception here only if I build project as (release)

   CopyProperties<T>(source, result, type);
   DeepCopyChildren<T>(source, result);

   return result;
}
Run Code Online (Sandbox Code Playgroud)

例外是:

System.Private.Reflection.Execution.dll中出现"System.MissingMethodException"类型的异常,但未在用户代码中处理

其他信息:MissingConstructor_Name,Windows.UI.Xaml.Controls.RelativePanel.有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=623485

我发现这个异常的一些相关的问题,但他们都指向缺少的库或类似更新库,但在我的应用程序没有任何改变.

Mar*_*und 6

此问题与UWP应用程序的发布版本使用.NET本机工具链有关.在这种模式下,反射需要一些提示才能正常工作.显然,它的构造函数RelativePanel不可用于反射.

幸运的是,有一个解决方法,如本博文中所述.

在您的UWP项目的Properties文件夹中是一个名为的文件default.rd.xml.打开它并在<Applications>元素中添加以下行:

<Type Name="Windows.UI.Xaml.Controls.RelativePanel" 
      Dynamic="Required All" Activate="Required All" /> 
Run Code Online (Sandbox Code Playgroud)

Dynamic属性应该确保可以反射,并且Activate属性应该确保构造函数可用于激活 - 这对于您的情况是关键的.

这应该包括所有RelativePanel反射成员,一切都应该按预期工作.

您可以在此处查看有关default.rd.xml文件结构的更多详细信息.