jeudi 15 novembre 2018

Dynamically add handler with a generic method to an event using Reflection

I have an event that looks like this:

public event EventHandler<DateTime> ValueChanged;

And an event handler method that looks like this:

public void ValueChangedHandler<T>(object sender, T e)
{
}

Now I want to add a handler to the event which would be the method described above.

I know it's possible, because when I use a static assign of the event handler everything is fine

ValueChanged += ValueChangedHandler;

But I want to do this during the runtime so I use Reflection:

var @event = GetType().GetEvent(nameof(ValueChanged));
var method = GetType().GetMethod(nameof(ValueChangedHandler));
var @delegate = Delegate.CreateDelegate(@event.EventHandlerType, this, method);
@event.AddEventHandler(this, @delegate);

And then I'm getting a System.ArgumentException "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.".

Apparently I'm missing something in adding a handler which consists of a generic method but my question is what is it?


Small research I've done before I decided to try the generic event thandler method:

I tried to add a handler with a method that looked like this:

public void ValueChangedHandler(object sender, object e)
{
}

But then I got not only a runtime error but I couldn't even add such handler statically. I received a compile error No overload for 'ValueChangedHandler(object, object)' matches delegate 'EventHandler<DateTime>' which I don't quite understand because System.DateTime eventually derives from System.Object, doesn't it?





Aucun commentaire:

Enregistrer un commentaire