Subscribe to an event using Reflection

I have a very simple class:

class Trace { void WriteTrace() { Console.WriteLine("Trace !"); } } 

I want this class to subscribe to an event, such as a form control load event. Management and event are defined dynamically, so I want to use reflection for this. I am trying something like this:

In my Trace class, I have this method:

 public void SubscribeEvent (Control control) { if (type.IsAssignableFrom(control.GetType())) { Trace test = this; MethodInfo method = typeof(Trace).GetMethod("WriteTrace"); // Subscribe to the event EventInfo eventInfo = control.GetType().GetEvent("Load"); // We suppose control is a form Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, control, method); // ERROR : Error binding to target method } } } 

There is an error in the last line: Error binding to the target method. What is wrong in my fragment?

Thanks!

EDIT : Ok, there’s no more error, but when the “Download” event is added from the form, the WriteTrace method is not called (I set a breakpoint, but it isn’t reached), why?

Sorry for editing, it works very well :)

+7
reflection events
source share
2 answers

With a few changes, I was able to complete your sample.

First, the Trace method must have a different signature that matches the EventHandler type:

 public class Trace { public void WriteTrace(object sender, EventArgs e) { Console.WriteLine("Trace !"); } } 

Then a few changes were made to SubscribeEvent :

 public void SubscribeEvent(Control control) { if (typeof(Control).IsAssignableFrom(control.GetType())) { Trace test = this; MethodInfo method = typeof(Trace).GetMethod("WriteTrace"); EventInfo eventInfo = control.GetType().GetEvent("Load"); // Create the delegate on the test class because that where the // method is. This corresponds with `new EventHandler(test.WriteTrace)`. Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, test, method); // Assign the eventhandler. This corresponds with `control.Load += ...`. eventInfo.AddEventHandler(control, handler); } } 

Hope this helps.

+8
source share

Your first problem is that the signature of the Trace.WriteTrace method does not match the syntax of the Form.Load event handler

Try the following:

 void WriteTrace(object sender, EventArgs e) { Console.WriteLine("Trace !"); } 

In addition, your CreateDelegate call should pass a trace object, not a control object:

 Trace test = this; MethodInfo method = typeof(Trace).GetMethod("WriteTrace"); // Subscribe to the event EventInfo eventInfo = control.GetType().GetEvent("Load"); // We suppose control is a form Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, method); // ERROR : Error binding to target method eventInfo.AddEventHandler(control, handler); 
+1
source share

All Articles