2012-04-30 55 views
0

我想動態加載一個dll並構造一個MyDllClass對象。我的代碼大致如下(剝離unrelevant份):使用反射動態鏈接一個dll並傳遞代表

MyDllClass.cs

namespace MyDllNameSpace 
{ 
    public class MyDllClass 
    { 

     private EventCallBack m_DelegateCallBack = null; 

     public MyDllClass(EventCallBack eventCallBack) 
     { 
      m_DelegateCallBack = eventCallBack; 
     } 

     public MyDllClass() 
     { 
     } 
     ... 
    } 
} 

MyDllCallBackNameSpace.cs

namespace MyDllCallBackNameSpace 
{ 
    public delegate void EventCallBack(string message); 
} 

我管理使用空構造來構造對象但我無法得到其他構造函數的工作。我得到ArgumentException

at System.Reflection.RuntimeConstructorInfo.InternalInvoke() 
at System.Reflection.RuntimeConstructorInfo.Invoke() 
at System.Reflection.ConstructorInfo.Invoke() at MyProgram.InitMyObject() 
at ... 

這裏是我的代碼:

MyProgram.cs

public void InitMyObject(EventCallBack callBack) 
    System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(DLL_PATH); 
    Type type = assembly.GetType(CLASS_NAME); 
    ConstructorInfo[] constructors = type.GetConstructors(); 
    if (type != null) 
    { 
     // empty constructor, works!!! 
     //return constructors[1].Invoke(new object[0]); 
     // This one gives InvalidArgument exception 
     return constructors[0].Invoke(new object[] {callBack}); 
    } 
    return null; 
} 

MyDllCallBackNameSpace.cs文件已經被添加到兩個項目(.dll文件&的.exe項目)和引用驅動器上的同一物理文件。但我懷疑它仍然被視爲不同。任何想法爲什麼它不工作,或任何解決方法?

+0

詢問你需要的*特定*構造函數。現在,使用構造函數[0]是一個骰子。改爲使用Type.GetConstructor()並傳遞'new Type [] {typeof(EventCallback)}'如果從GetConstructor返回null,那麼EventCallback出現在多個程序集中。 –

回答

0

我設法解決這個買移動MyDllCallBackNameSpace.cs到另一個DLL。然後我從兩個項目中引用該dll。

0

對於ConstructorInfo.Invoke Method (Object[])的ArgumentException異常說:「參數數組不包含與此構造函數接受的類型相匹配的值。你確定當你做constructors[0]時,你會得到你期望的構造函數嗎?嘗試ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(EventCallback) });而不是GetConstructors。

+0

在這種情況下,GetConstructor'返回null。雖然我傳遞了相同類型的'EventCallback'參數。我想我也需要在運行時動態創建參數。 – Caner

+0

如果你這樣做,你會得到什麼'Type callbackType = assembly.GetType(「EventCallBack」); ConstructorInfo constructor = type.GetConstructor(new Type [] {callbackType});'? – JamieSee

+0

'assembly.GetType(「EventCallBack」);'返回null – Caner