If I have a type that inherits from EventArgs (lets call it EventArgs1), and a further bunch of classes that inherit from EventArgs1 (lets call them collectively EventArgsX), and then a bunch of events that are are of the type EventHandler<EventArgsX>, if at runtime I am passed the EventInfo for one of these events and I want to add an event handler that expects a second argument of type EventArgs1 (e.g. MyEventHandler(object sender, EventArgs1 e)) how would I do it?
If the event was of type EventHandler<EventArgs1> then I would just 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 simply new up an EventHandler<EventArgsX> If I did know which event I was adding the handler to at compile time then this would be entirely acceptable:
MyEvent += MyEventHandler
But I simply can’t work out how to do this at runtime. Any suggestions?
Sure you can, although you need to do it using
Delegate.CreateDelegate()and reflection. AssumingMyEventHandleris an instance method onthis, you could do it like this: