C#获取委托绑定数量

 

 获取委托绑定数量

 /// <summary>
        /// 获取指定事件绑定的委托数量
        /// </summary>
        /// <param name="obj">拥有事件的对象</param>
        /// <param name="eventName">事件名称</param>
        /// <returns>委托数量,如果无法获取则返回-1</returns>
        public static int GetEventHandlerCount(object obj, string eventName)
        {
            if (obj == null) throw new ArgumentNullException(nameof(obj));
            if (string.IsNullOrEmpty(eventName)) throw new ArgumentNullException(nameof(eventName));

            Type type = obj.GetType();
            FieldInfo eventField = type.GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic);

            // 如果事件是使用EventHandlerList存储的(如WinForms控件中的事件)
            if (eventField == null)
            {
                // 尝试获取事件属性
                EventInfo eventInfo = type.GetEvent(eventName);
                if (eventInfo == null)
                {
                    throw new ArgumentException($"事件 {eventName} 在类型 {type.Name} 中未找到。");
                }

                // 对于EventHandlerList存储的事件,我们需要获取EventHandlerList字段
                FieldInfo eventHandlerListField = type.GetField("events", BindingFlags.Instance | BindingFlags.NonPublic);
                if (eventHandlerListField == null)
                {
                    // 有时可能是别名字段,尝试获取默认的事件字段
                    eventHandlerListField = type.GetField("Events", BindingFlags.Instance | BindingFlags.NonPublic);
                }

                if (eventHandlerListField != null)
                {
                    EventHandlerList eventHandlerList = eventHandlerListField.GetValue(obj) as EventHandlerList;
                    if (eventHandlerList != null)
                    {
                        // 获取事件的关键字(key)
                        PropertyInfo eventKeyProperty = type.GetProperty("Event" + eventName, BindingFlags.Static | BindingFlags.NonPublic);
                        if (eventKeyProperty != null)
                        {
                            object key = eventKeyProperty.GetValue(null);
                            Delegate handler = eventHandlerList[key];
                            return handler?.GetInvocationList().Length ?? 0;
                        }
                    }
                }

                // 如果无法通过EventHandlerList获取,尝试直接获取委托字段(通常事件字段名为事件名)
                eventField = type.GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic);
            }

            // 如果是普通的委托字段
            if (eventField != null)
            {
                Delegate eventDelegate = eventField.GetValue(obj) as Delegate;
                return eventDelegate?.GetInvocationList().Length ?? 0;
            }

            // 如果以上方法都无法获取,则返回-1表示失败
            return -1;
        }

 

posted @ 2026-02-02 16:56  家煜宝宝  阅读(2)  评论(0)    收藏  举报