簡體   English   中英

無法使用Activator.CreateInstance創建對象

[英]not able to create object with Activator.CreateInstance

我正在嘗試通過使用以下代碼在我的項目中加載farpoint dll的舊版本

     System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(@"FarPoint.Web.Spread.dll");
    System.Type MyDLLFormType = assembly.GetType("FarPoint.Web.Spread.FpSpread");
    var c = Activator.CreateInstance(MyDLLFormType);

問題是創建實例后,farpoint的所有可用方法均不可用[例如-如果我直接創建對象,則實例可以使用saveExcel或savechanges之類的方法]

                FpSpread fpProxyObject = new FpSpread();
                fpProxyObject.SaveExcel();

它們可用,只是在編譯時不可用。 Activator.CreateInstance()返回一個object 您當然可以投射對象:

var c = Activator.CreateInstance(...)
FpSpread fpProxyObject = (FpSpread)c;

但這可能會超出使用反射創建實例的全部目的。

您可以使用反射來訪問結果對象的所有成員,即:

MethodInfo saveExcelMethod = c.GetType().GetMethod("SaveExcel");
if (saveExcelMethod == null) throw new ApplicationException("Incorrect version of FarPoint");
saveExcelMethod.Invoke(c);

Intellisense無法正常工作,因為正如@ C.Evenhuis所述, Activator.CreateInstance返回object ,因此您應該將其強制轉換為適當的類型。

如果類型在編譯時未知,但是您可以訪問代碼庫,則可以嘗試為它添加接口,並由您的類實現。 然后將對象投射到該接口並使用它。 (我不知道您的目的,但是可以將接口視為所有類型的合同,您將動態加載該接口)。

如果類型在編譯時未知,並且您無權訪問代碼庫,則可以使用反射進行方法調用或使用dynamic方法。

dynamic c = Activator.CreateInstance(MyDLLFormType);
c.SaveExcel(); // this method invocation will be bound in runtime.

順便說一句,在使用Assembly.LoadFile要小心。 您可能會從本文中獲得更多詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM