gpt4 book ai didi

c# - Activator.CreateInstance(type) 抛出异常

转载 作者:行者123 更新时间:2023-11-30 14:24:11 26 4
gpt4 key购买 nike

实际上这是一个非常奇怪的异常,因为它只在我将项目构建为Release 时发生,而在我选择Debug 时根本不会发生。在 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;
}

异常(exception)情况是:

An exception of type 'System.MissingMethodException' occurred in System.Private.Reflection.Execution.dll but was not handled in user code

Additional information: MissingConstructor_Name, Windows.UI.Xaml.Controls.RelativePanel. For more information, visit http://go.microsoft.com/fwlink/?LinkId=623485

我发现了一些与此异常相关的问题,但它们都指向缺少库或更新库,如 this但没有改变我的应用程序中的任何内容。

最佳答案

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

幸运的是,有一个解决方法,如 this blogpost 中所述.

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

<Type Name="Windows.UI.Xaml.Controls.RelativePanel" 
Dynamic="Required All" Activate="Required All" />

Dynamic属性应确保反射是可能的,并且 Activate属性应确保构造函数可用于激活 - 这是您的案例的关键。

这应该包括 RelativePanel 的所有成员进行反射(reflection),一切都应该按预期进行。

您可以在 default.rd.xml 上查看更多详细信息文件结构 here .

关于c# - Activator.CreateInstance(type) 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42185670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com