首页 > 代码库 > C# 反射
C# 反射
/// <summary> /// 清除控件的事件 /// </summary> /// <param name="objectHasEvents"></param> /// <param name="EventFiledName"></param> public static void ClearAllEvents(Control objectHasEvents, string EventFiledName) { if (objectHasEvents == null) { return; } EventInfo[] events = objectHasEvents.GetType().GetEvents( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (events == null || events.Length < 1) { return; } for (int i = 0; i < events.Length; i++) { try { EventInfo ei = events[i]; /******************************************************** * class的每个event都对应了一个同名的private的delegate类 * 型成员变量(这点可以用Reflector证实)。因为private成 * 员变量无法在基类中进行修改,所以为了能够拿到base * class中声明的事件,要从EventInfo的DeclaringType来获取 * event对应的成员变量的FieldInfo并进行修改 ********************************************************/ //FieldInfo fi = ei.DeclaringType.GetField("EVENT_SELECTEDVALUECHANGED", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static); FieldInfo fi = null; if (EventFiledName == null) fi = ei.DeclaringType.GetField(ei.Name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static); else fi = ei.DeclaringType.GetField(EventFiledName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static); if (fi != null) { // 将event对应的字段设置成null即可清除所有挂钩在该event上的delegate fi.SetValue(objectHasEvents, null); } } catch { } } if (objectHasEvents is BizMagCardTextBox) { RemoveEvent(objectHasEvents, "EventEnter", "Enter"); RemoveEvent(objectHasEvents, "EventKeyPress", "KeyPress"); } if (objectHasEvents is SDUnionICAndMagCard) { RemoveEvent(objectHasEvents, "EventEnter", "Enter"); } if (objectHasEvents is BizComboBox) { RemoveEvent(objectHasEvents, "EVENT_SELECTEDINDEXCHANGED", "SelectedIndexChanged"); } } /// <summary> /// 去掉指定控件的指定事件 /// </summary> /// <param name="con">当前的控件</param> /// <param name="eventName">事件名称</param> /// <param name="infoName">对应的field名称</param> public static void RemoveEvent(Control con, string eventName, string infoName) { try { BindingFlags mPropertyFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic;//筛选 EventInfo[] events = con.GetType().GetEvents(mPropertyFlags); Type type = typeof(Control); PropertyInfo propertyInfo = type.GetProperty("Events", mPropertyFlags); EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(con, null);//事件列表 foreach (EventInfo ei in events) { if (ei.Name.Equals(infoName)) { FieldInfo fieldInfo = ei.DeclaringType.GetField(eventName, mPropertyFlags); Delegate d = eventHandlerList[fieldInfo.GetValue(con)];//获得对应的事件委托 if (d == null) return; foreach (Delegate dx in d.GetInvocationList()) { ei.RemoveEventHandler(con, dx); //移除对应的事件 } } } } catch (Exception ex) { } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。