C#Relection addeventhandler:create Delegate fail无法绑定到目标方法

时间:2015-12-11 10:05:48

标签: c# reflection delegates

我试图从外部dll文件中添加事件,并且我得到了参数#34;无法绑定到目标方法,因为它的签名或安全透明度与委托类型"

不兼容。

我尝试搜索解决方案,但它们无法使用我的代码。

这是dll文件中的代码。

public class StartProcess
{
     public StartProcess(){}

     public delegate void MSTStepInformEventHandler(object sender, MSTStepInformEventArg e);
     public event MSTStepInformEventHandler StepInformed;

     protected virtual void OnStepInformed(MSTStepInformEventArg e) 
     {
          if (this.StepInformed != null)
          {
               this.StepInformed(this, e);
          }
     }

     public void Start()
     {
          this.OnStepInformed(new MSTStepInformEventArg() { Info = DateTime.Now.toString()});
     }

public class MSTStepInformEventArg : EventArgs
{
    public MSTStepInformEventArg() { }
    public string Info { get; set; }
}

以下是反思代码。

class Test
{
    void HandleEvent(object sender, MainDLL.MSTStepInformEventArg e)
    {
        Console.WriteLine("HandleEvent called " + e.Info);
    }

    static void Main()
    {
        Assembly ass = Assembly.LoadFrom("StartProcess.dll");

        Type classEx = ass.GetType("StartProcess.StartProcess");

        Test test = new Test();

        object obj = Activator.CreateInstance(classEx);

        MethodInfo method = typeof(Test).GetMethod("HandleEvent", BindingFlags.NonPublic | BindingFlags.Instance);

        EventInfo eventInfo = classEx.GetEvent("StepInformed");

        Type type = eventInfo.EventHandlerType;

        Delegate handler = Delegate.CreateDelegate(type, test, method); // Exception throw is here -----

        eventInfo.AddEventHandler(obj, handler);

        classEx.InvokeMember("Start", BindingFlags.InvokeMethod, null, obj, null);
    }
}

请帮忙......

0 个答案:

没有答案