Remove all the EventHandlers of the object by reflection

来源:互联网 发布:银行家算法的基本思想 编辑:程序博客网 时间:2024/06/11 04:32
[c-sharp] view plaincopy
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             Customer c = new Customer();  
  6.             EventInfo evt = c.GetType().GetEvent("OnChange",  
  7.                     BindingFlags.NonPublic | BindingFlags.Instance  
  8.                     | BindingFlags.Public  
  9.                 );  
  10.             // 添加一个事件关联  
  11.             evt.AddEventHandler(c, new EventHandler(c_OnChange));  
  12.             // 添加第二个事件关联  
  13.             evt.AddEventHandler(c, new EventHandler(c_OnChange));  
  14.   
  15.             // 删除全部事件关联。  
  16.             RemoveEvent<Customer>(c, "OnChange");  
  17.   
  18.             c.Change();  
  19.         }  
  20.   
  21.         static void c_OnChange(object sender, EventArgs e)  
  22.         {  
  23.             Console.WriteLine("事件被触发了");  
  24.         }  
  25.   
  26.         static void RemoveEvent<T>(T c, string name)  
  27.         {  
  28.             Delegate[] invokeList = GetObjectEventList(c, name);  
  29.             if (invokeList == null)  
  30.                 return;  
  31.             foreach (Delegate del in invokeList)  
  32.             {  
  33.                 typeof(T).GetEvent(name).RemoveEventHandler(c, del);  
  34.             }  
  35.         }  
  36.   
  37.         public static Delegate[] GetObjectEventList(object p_Object, string p_EventName)  
  38.         {  
  39.             // Get event field  
  40.             FieldInfo _Field = p_Object.GetType().GetField(p_EventName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);  
  41.             if (_Field == null)  
  42.             {  
  43.                 return null;  
  44.             }  
  45.             // get the value of event field which should be a delegate  
  46.             object _FieldValue = _Field.GetValue(p_Object);  
  47.   
  48.             // if it is a delegate  
  49.             if (_FieldValue != null && _FieldValue is Delegate)  
  50.             {  
  51.                 // cast the value to a delegate  
  52.                 Delegate _ObjectDelegate = (Delegate)_FieldValue;  
  53.                 // get the invocation list  
  54.                 return _ObjectDelegate.GetInvocationList();  
  55.             }  
  56.             return null;  
  57.         }   
  58.     }  
  59.   
  60.     class Customer  
  61.     {  
  62.         public event EventHandler OnChange;  
  63.         public void Change()  
  64.         {  
  65.             if (OnChange != null)  
  66.                 OnChange(thisnull);  
  67.             else  
  68.                 Console.WriteLine("no event attached");  
  69.         }  
  70.     }  
原文地址:http://blog.csdn.net/diandian82/article/details/5738299
原创粉丝点击