[英]Dynamically create class with Constructor that calls another Static class method
I'm trying to dynamically create an instance of class CommandDrawing
which is in another assembly. 我试图动态创建另一个程序
CommandDrawing
类的实例。 The CommandDrawing
class default constructor contains calls to static methods which are inanother another class in the same assembley. CommandDrawing
类的默认构造函数包含对静态方法的调用,这些静态方法是同一汇编中的另一个类。 The dynamic class is created but when it trys to run the static method call in the constructor it falls over with exception: 创建了动态类,但是当它尝试在构造函数中运行静态方法调用时,它将发生异常:
Exception has been thrown by the target of an invocation.
调用的目标已引发异常。 TypeInitializeException`The type initializer for threw an exception.
TypeInitializeException`用于引发异常的类型初始值设定项。
Do I have to load in both classes and if so how? 我是否必须在两个类中都加载?
I use code below to create the class which I've used successfully before and works when the static method calls are not there: 我使用下面的代码来创建之前成功使用过的类,并且当不存在静态方法调用时可以使用该类:
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 });
The CommandDrawing
default constructor looks like below - note UtilityMapControl.SetupDrawingTableTemplate
is the static method I'm calling and it falls over here: 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);
}
Maybe a dependency could not be loaded. 也许无法加载依赖项。 If the type initializer uses a type from another Assembly that could happen, because
LoadFile
doesn't resolve dependencies as you might expect. 如果类型初始值设定项使用的是来自另一个Assembly的类型,则可能会发生这种情况,因为
LoadFile
不会像您期望的那样解析依赖项。 MSDN says : MSDN说 :
LoadFile
does not load files into theLoadFrom
context, and does not resolve dependencies using the load path, as theLoadFrom
method does.LoadFile
不会将文件加载到LoadFrom
上下文中,也不会像LoadFrom
方法那样使用加载路径解析依赖项。
So i suggest using LoadFrom
instead of LoadFile
. 所以我建议使用
LoadFrom
而不是LoadFile
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.