简体   繁体   中英

Why can't I get the event handler of a LinkButton's event using reflection?

I want to access the event handler of a LinkButton 's Command event, but in the snippet bellow fieldInfo is null.

LinkButton button = new LinkButton();
button.Command += (s, e) => { };
Type type = button.GetType();
EventInfo[] eventInfos = type.GetEvents(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (EventInfo eventInfo in eventInfos)
    if (eventInfo.Name == "Command")
    {
        // fieldInfo is null
        FieldInfo fieldInfo = eventInfo.DeclaringType.GetField(eventInfo.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
        Delegate delegates = (Delegate)fieldInfo.GetValue(button);
        foreach (Delegate handler in delegates.GetInvocationList())
        {
            eventInfo.RemoveEventHandler(button, handler);
            // or
            eventInfo.AddEventHandler(button, handler);
            // or do whatever with handler
        }
    }

Code snippet was inspired from this .

Why is fieldInfo null ?

Is there another way to get the event handler of a LinkButton 's Command event ?

Also Hans Passant sollution does not work on LinkButton using Command as the field name.

Looking at the LinkCommand reference source :

public event CommandEventHandler Command is "magic".

LinkCommand uses the baseclass UI.Control and the events are stored in a protected EventHandlerList Events .

LinkCommand also has a private property called EventCommand , which appears to be used as the indexer for the Events list.

If I'm reading the source correctly, you'll need to extract Events[EventCommand] and cast it to CommandEventHandler like LinkButton does in OnCommand .

This also appears to be a common practice for classes using UI.Control as a base class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM