vendredi 11 décembre 2015

C# Relection addeventhandler : create Delegate fail cannot bind to the target method

I have tried to add event from external dll file and i got argumentexception "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type".

I tried to search the solution but they do not work with my code.

This is code in dll file.

public class StartProcess
{
     public StartProcess(){}

     public delegate void MSTStepInformEventHandler(object sender, MSTStepInformEventArg e);
     public event MSTStepRetryRequestEventHandler StepInformed;
     protected virtual void OnStepInformed(MSTStepInformEventArg e) 
     {
          if (this.StepRetryRequest != null)
          {
               this.StepRetryRequest(this, e);
          }
     }
     public void Start()
     {
          this.OnStepInformed(new MSTStepInformEventArg() { Info = DateTime.Now.toString()});
}
public class MSTStepInformEventArg : EventArgs
{
    public MSTStepInformEventArg() { }
    public string Info { get; set; }
}

And the below is reflection code.

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);
    }
}

Please help...





Aucun commentaire:

Enregistrer un commentaire