我想動態加載一個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]是一個骰子。改爲使用Type.GetConstructor()並傳遞'new Type [] {typeof(EventCallback)}'如果從GetConstructor返回null,那麼EventCallback出現在多個程序集中。 –