WinForms/.NET: How to get the event handler attach

2019-09-04 19:55发布

问题:

How can i get the event handler attached to an event?

pseudocode, for example's sake:

public static EventHandler GetChangeUICuesEventHandler(Control SomeControl)
{
   EventHandler changeUICuesEventHandler = SomeControl.ChangeUICues;
   return changeUICuesEventHandler
}

Sample usage (pseudo-code):

Control control = GetControlByName(Console.ReadLine());
button1.ChangeUICues += GetChangeUICuesEventHandler(control);

回答1:

I offer up the following as an alternative path rather than a direct answer... So here goes...

Can you approach this a little differently perhaps by ensuring that your control with the event handler already attached, in this case the parameter someControl, instead implements an interface that defines the attached handler. For example:

public interface ChangUICuesHandler
{
    void OnChangeUICues(object sender, EventArgs e);
}

Then you could use it like so:

Control control = GetControlByName(Console.ReadLine());
if (!(control is ChangeUICuesHandler))
{
    throw new Exception("Input Control does not implement the interface");
}
var handlerControl = control as ChangeUICuesHandler;
button.ChangeUICues += handler.OnChangeUICues;