How to get a delegate object from an EventInfo?

前端 未结 3 1688
盖世英雄少女心
盖世英雄少女心 2020-12-09 19:42

I need to get all events from the current class, and find out the methods that subscribe to it. Here I got some answers on how to do that, but I don\'t know how I can get th

3条回答
  •  北海茫月
    2020-12-09 20:01

    For my case, the field value (class ToolStripMenuItem, field EventClick) frustratingly is of type object, not delegate. I had to resort to the Events property that Les mentioned in his answer, in a way I got from here. The field EventClick in this case only holds the key to the EventHandlerList stored in this property.

    Some other remarks:

    • The rule fieldName = "Event" + eventName I employed will not work in every case. Unfortunately there is no common rule for linking the event name to the field name. You might try to use a static dictionary for the mapping, similar to this article.
    • I'm never quite sure about the BindingFlags. In another scenario, you might have to adjust them.

      /// 
      /// Gets the EventHandler delegate attached to the specified event and object
      /// 
      /// object that contains the event
      /// name of the event, e.g. "Click"
      public static Delegate GetEventHandler(object obj, string eventName)
      {
          Delegate retDelegate = null;
          FieldInfo fi = obj.GetType().GetField("Event" + eventName, 
                                                 BindingFlags.NonPublic | 
                                                 BindingFlags.Static |
                                                 BindingFlags.Instance | 
                                                 BindingFlags.FlattenHierarchy |
                                                 BindingFlags.IgnoreCase);
          if (fi != null)
          {
              object value = fi.GetValue(obj);
              if (value is Delegate)
                  retDelegate = (Delegate)value;
              else if (value != null) // value may be just object
              {
                  PropertyInfo pi = obj.GetType().GetProperty("Events",
                                                 BindingFlags.NonPublic |
                                                 BindingFlags.Instance);
                  if (pi != null)
                  {
                      EventHandlerList eventHandlers = pi.GetValue(obj) as EventHandlerList;
                      if (eventHandlers != null)
                      {
                          retDelegate = eventHandlers[value];
                      }
                  }
              }
          }
          return retDelegate;
      }
      

提交回复
热议问题