I have a very simple class :
class Trace
{
void WriteTrace()
{
Console.WriteLine("Trace !");
}
}
I want this class subscribes to an event, for example the load event of a form control. The control and event are define dynamically so I want to use reflection to do this I'm trying something like that :
In my class Trace 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 on the last line : Error binding to target method. What's wrong in my snippet ?
Thank you !
EDIT : Ok, there is no more error but when the event "Load" is raised from the Form, the method WriteTrace is not called (I have put a breakpoint but there is not reached). Why ?
Sorry for the edit, it works very fine :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…