GetField unable to obtain EventClick

别等时光非礼了梦想. 提交于 2021-01-28 07:12:12

问题


I am trying to determine the method that Click event is subscribed to, in my form, and I follow the guide here.

Whereas the forum post above able to get the list that the Click event is subscribing to by following code

 hasClickEventHandler = HasEventHandler(buttonControl, "EventClick");
    Assert.AreEqual(hasClickEventHandler, true);


    private bool HasEventHandler(Control control, string eventName)
    {
        EventHandlerList events =
            (EventHandlerList)
            typeof(Component)
             .GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance)
             .GetValue(control, null);

        object key = typeof(Control)
            .GetField(eventName, BindingFlags.NonPublic | BindingFlags.Static)
            .GetValue(null);

        Delegate handlers = events[key];

        return handlers != null && handlers.GetInvocationList().Any();
    }

I can't.

I then use var keys = typeof(Control).GetFields(BindingFlags.NonPublic | BindingFlags.Static); to check, and I found that one of the Keys does seem to have the correct event name. ie,

keys[19].FullName=="System.Windows.Forms.Control.EventClick";
keys[19].Name=="EventClick";

So there is no reason why

object key = typeof(Control).GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static)

And

object key = typeof(Control).GetField("System.Windows.Forms.Control.EventClick", BindingFlags.NonPublic | BindingFlags.Static)

Returns null, and yet this is exactly what happen

Why is this so? What could have gone wrong?

Here's my exact code

        var form = new Form1();
        EventHandlerList events = (EventHandlerList)typeof(Control)
            .GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance)
            .GetValue(form, null);
        var keys = typeof(Control).GetFields(BindingFlags.NonPublic | BindingFlags.Static);
        var name = keys[19].Name;  //name="EventClick"
       object key = typeof(Control).GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static);  //null

Edit: I can reproduce the behavior on .Net 4.5.2, however, on .Net 4.6, key is a valid object. This seems to be a specific bug in .Net 4.5.2


回答1:


My solution: Changing the target from .Net 4.5.2 to .Net 4.6 fixes the issue; in .Net 4.6

 object key = typeof(Control).GetField("EventClick", BindingFlags.NonPublic | BindingFlags.Static);

key gives a valid object



来源:https://stackoverflow.com/questions/43717818/getfield-unable-to-obtain-eventclick

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!