How to add a more general event handler to an event at runtime

If I have a type that inherits from EventArgs (allows it to be called by EventArgs1) and another group of classes that inherit from EventArgs1 (lets call them together EventArgsX), and then a bunch of events that are of type EventHandler<EventArgsX>if I passed EventInfo at runtime for one of these events, and I want to add an event handler that expects a second argument of type EventArgs1 (for example MyEventHandler(object sender, EventArgs1 e)), how would I do this?

If the event was of type EventHandler<EventArgs1>, then I would simply do this:

eventInfo.AddEventHandler(this, new EventHandler<EventArgs1>(MyEventHandler));

But this throws an exception when the event is of type EventHandler<EventArgsX>, and since I don't know what EventArgsX is at compile time, I can't just update EventHandler<EventArgsX>. If I knew what event I was adding a handler at compile time, this would be perfectly acceptable:

MyEvent += MyEventHandler

But I just can't figure out how to do this at runtime. Any suggestions?

+3
source share
2 answers

I can’t just update EventHandler<EventArgsX>

Of course you can, although you need to do this using Delegate.CreateDelegate()reflection. Assuming that MyEventHandleris an instance method on this, you can do it like this:

var eventInfo = …;

EventHandler<EventArgs1> badHandler = MyEventHandler;

var goodHandler = Delegate.CreateDelegate(
    eventInfo.EventHandlerType, this, badHandler.Method);

eventInfo.AddEventHandler(this, goodHandler);
+4
source

UPDATE

, ; , -, , .


, , . , EventArgs . , .

,

class EventArgs1 : EventArgs {}
class EventArgsA : EventArgs1 {}
class EventArgsB : EventArgs1 {}

, , void Handle(object sender, EventArgsA args) void SomeEvent(object sender, EventArgs1 args). :

if (SomeEvent != null)
{
    var args = new EventArgsB();
    SomeEvent(this, args);      //this line is perfectly legal, as EventArgsB inherits from EventArgs1.
}

, , args Handle(object, EventArgsA), , , , EventArgsB EventArgsA . . , , .

0

All Articles