繁体   English   中英

使用构造函数动态创建类,该构造函数调用另一个静态类方法

[英]Dynamically create class with Constructor that calls another Static class method

我试图动态创建另一个程序CommandDrawing类的实例。 CommandDrawing类的默认构造函数包含对静态方法的调用,这些静态方法是同一汇编中的另一个类。 创建了动态类,但是当它尝试在构造函数中运行静态方法调用时,它将发生异常:

调用的目标已引发异常。 TypeInitializeException`用于引发异常的类型初始值设定项。

我是否必须在两个类中都加载?

我使用下面的代码来创建之前成功使用过的类,并且当不存在静态方法调用时可以使用该类:

Assembly assemblyCommandDrawing = System.Reflection.Assembly.LoadFile(@"D:\ManifoldInspections.dll");
Type typeCommandDrawing = assemblyCommandDrawing.GetType("InspectionDetails.CommandDrawing");
object cmd = System.Activator.CreateInstance (typeCommandDrawing, new object[] { drawing, DrawingBaseDetail });

CommandDrawing默认构造函数如下所示-注意UtilityMapControl.SetupDrawingTableTemplate是我正在调用的静态方法,它落在这里:

public CommandDrawing(Manifold.Interop.Drawing p_Drawing, InspectionDetails.DrawingBaseDetail p_ClassDetailTemplate)
{
  this.Drawing = p_Drawing;
  //this.ClassDetailTemplate = p_ClassDetailTemplate.GetType();
  this.ClassDetailTemplate = p_ClassDetailTemplate;
  ManifoldInspections.Utility.UtilityMapControl.SetupDrawingTableTemplate(this.Drawing, p_ClassDetailTemplate);
}

也许无法加载依赖项。 如果类型初始值设定项使用的是来自另一个Assembly的类型,则可能会发生这种情况,因为LoadFile不会像您期望的那样解析依赖项。 MSDN说

LoadFile不会将文件加载到LoadFrom上下文中,也不会像LoadFrom方法那样使用加载路径解析依赖项。

所以我建议使用LoadFrom而不是LoadFile

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM