Remove all the EventHandlers of the object by reflection
来源:互联网 发布:银行家算法的基本思想 编辑:程序博客网 时间:2024/06/11 04:32
- class Program
- {
- static void Main(string[] args)
- {
- Customer c = new Customer();
- EventInfo evt = c.GetType().GetEvent("OnChange",
- BindingFlags.NonPublic | BindingFlags.Instance
- | BindingFlags.Public
- );
- // 添加一个事件关联
- evt.AddEventHandler(c, new EventHandler(c_OnChange));
- // 添加第二个事件关联
- evt.AddEventHandler(c, new EventHandler(c_OnChange));
- // 删除全部事件关联。
- RemoveEvent<Customer>(c, "OnChange");
- c.Change();
- }
- static void c_OnChange(object sender, EventArgs e)
- {
- Console.WriteLine("事件被触发了");
- }
- static void RemoveEvent<T>(T c, string name)
- {
- Delegate[] invokeList = GetObjectEventList(c, name);
- if (invokeList == null)
- return;
- foreach (Delegate del in invokeList)
- {
- typeof(T).GetEvent(name).RemoveEventHandler(c, del);
- }
- }
- public static Delegate[] GetObjectEventList(object p_Object, string p_EventName)
- {
- // Get event field
- FieldInfo _Field = p_Object.GetType().GetField(p_EventName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
- if (_Field == null)
- {
- return null;
- }
- // get the value of event field which should be a delegate
- object _FieldValue = _Field.GetValue(p_Object);
- // if it is a delegate
- if (_FieldValue != null && _FieldValue is Delegate)
- {
- // cast the value to a delegate
- Delegate _ObjectDelegate = (Delegate)_FieldValue;
- // get the invocation list
- return _ObjectDelegate.GetInvocationList();
- }
- return null;
- }
- }
- class Customer
- {
- public event EventHandler OnChange;
- public void Change()
- {
- if (OnChange != null)
- OnChange(this, null);
- else
- Console.WriteLine("no event attached");
- }
- }
原文地址:http://blog.csdn.net/diandian82/article/details/5738299
- Remove all the EventHandlers of the object by reflection
- Remove all the EventHandlers of the object by reflection
- Remove all the EventHandlers of the object by reflection (C#清空事件)
- Learning the parts of object by NMF
- Learning the parts of object by NMF
- remove all the same elements
- All of the previous
- The Beginning Of All
- Javascript Object Method Properties console.log View all methods and properties of the object
- 反射规则 the law of reflection
- The reflection of Java language (二)
- GCC - the root of all
- All the versions of STL
- List All Of The Subsets
- In all of the functions
- All of the previous lessons
- The rest of all reasons
- The Methods of class Object
- Android之Bitmap用法汇总
- 邮件群发的分别发送功能
- A. Reconnaissance 2
- poj 1018
- uva 10420
- Remove all the EventHandlers of the object by reflection
- c++ 如何获取系统时间
- Android TextWatcher监控EditText中的输入内容并限制其输入字符个数
- 数据库设计5步骤
- AssetBundle 【unity3d教程】
- phantomjs html to PDF
- 高斯日记
- C 语言和C++语言的 struct对比 & struct和typedef struct
- 算法学习与实践之插入排序