C#动态创建两个按钮,btn2复制btn1的Click事件,匿名委托

时间:2021-08-31 05:12:26

#region//取一个控件的事件托管清单:getComponentEventDelegates /// <summary> /// 取一个控件的事件托管清单,例如想判断一个GridView是否定义了PageIndexChanging事件 /// 从CSDN搜来的: /// </summary> /// <param>组件对象实例</param> /// <param>事件的名称,如:Click</param> /// <param>事件委托类型,如"ItemClickEventHander"</param> /// <returns></returns> public static Delegate[] getComponentEventDelegates(object component, string EventName, string EventHandlerTypeName) { //取控件的类型、属性列表、事件托管列表、头字段列表 Type componentType = component.GetType(); PropertyInfo eventsPropertyInfo = componentType.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic); EventHandlerList eventHanlderList = eventsPropertyInfo.GetValue(component, null) as EventHandlerList; FieldInfo HeadFieldInfo = eventHanlderList.GetType().GetField("head", BindingFlags.Instance | BindingFlags.NonPublic); object HeadObject = HeadFieldInfo.GetValue(eventHanlderList); // do { FieldInfo[] fieldInfoList = componentType.GetFields(BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fieldInfoList) { object fieldValue = fieldInfo.GetValue(component); if (fieldValue != null) { Type fieldType = fieldValue.GetType(); if (fieldType.Name == EventHandlerTypeName && (fieldValue as Delegate) != null) { return (fieldValue as Delegate).GetInvocationList(); } else if (fieldType.Name == typeof(Object).Name) { if (fieldInfo.Name.IndexOf(EventName, StringComparison.OrdinalIgnoreCase) > -1) { if (HeadObject != null) { Delegate delegateObject = eventHanlderList[fieldValue]; if (delegateObject != null) return delegateObject.GetInvocationList(); } } } } } componentType = componentType.BaseType; } while (componentType != null); //循环结束 // if (HeadObject == null) return null; //没有 object ListEntry = HeadObject; Type ListEntryType = ListEntry.GetType(); FieldInfo handlerFieldInfo = ListEntryType.GetField("handler", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo keyFieldInfo = ListEntryType.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo nextFieldInfo = ListEntryType.GetField("next", BindingFlags.Instance | BindingFlags.NonPublic); while (ListEntry != null) { Delegate handler = handlerFieldInfo.GetValue(ListEntry) as Delegate; object key = keyFieldInfo.GetValue(ListEntry); ListEntry = nextFieldInfo.GetValue(ListEntry); if (handler != null && handler.GetType().Name == EventHandlerTypeName) return handler.GetInvocationList(); } return null; } #endregion