簡體   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