使用反射和传递委托动态链接dll

时间:2012-04-30 14:20:10

标签: c# reflection

我想动态加载一个dll并构造一个MyDllClass对象。我的代码大致如下(剥离了相关部分):

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项目)中,并在我的驱动器上引用相同的物理文件。但我怀疑它仍然被视为不同。任何想法为什么它不起作用,或任何变通方法?

2 个答案:

答案 0 :(得分:0)

ConstructorInfo.Invoke Method (Object[])的ArgumentException表示,“参数数组不包含与此构造函数接受的类型匹配的值。”当你constructors[0]时,你确定你得到了你期望的构造函数吗?尝试ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(EventCallback) });而不是GetConstructors。

答案 1 :(得分:0)

我设法解决这个购买动作MyDllCallBackNameSpace.cs到另一个dll。然后我从两个项目中引用了这个dll。

相关问题