views:

668

answers:

2

I'm am trying to add event handlers to 'myObject' based on the name of an event or events. 'myObject' has an event called 'MyEvent' and I have a public event handler called 'MyEventHandler' (which I don't need to get by name but do it below to get a MethodInfo).

This is what I have so far:

EventInfo eventInfo = myObject.GetType().GetEvent("MyEvent");
MethodInfo handlerInfo = GetType().GetMethod("MyEventHandler");

if (eventInfo != null && handlerInfo != null)
   eventInfo.AddEventHandler(
      this,
      Delegate.CreateDelegate(eventInfo.EventHandlerType, handlerInfo)
   );

I get this error:

Error binding to target method.

Am I on the right track or is there a better way?

+2  A: 

I had success with this code:

eventInfo.AddEventHandler(this, Delegate.CreateDelegate(typeof(eventInfo.EventHandlerType.FullName), this, "MyEventHandler"));

Edit: Added: eventInfoEventHandlerType.FullName so it's a little more dynamic based on the event handler type.

Chris Persichetti
Almost, I combined your answer with the other answer that just disappeared (using 'myObject' instead of this for the first parameter). Thank you both.
tpower
A: 

Example above doesn't work:

eventInfo.AddEventHandler(this, Delegate.CreateDelegate(typeof(eventInfo.EventHandlerType.FullName), this, "MyEventHandler"));

eventInfo.EventHandlerType.FullName - this is string

What would you suggest?

Spaniard