鹿我所录的博客

记录我在学习C#中的点点滴滴,记录下以备后来人借鉴。

 

清除一个对象所有事件所挂钩的delegate

using System.Reflection; //需在添加 这个引用
 
/// <summary> 
         
/// 清除一个对象所有事件所挂钩的delegate 
         
/// </summary> 
         
/// <param>有事件的对象</param> 
         public static void ClearAllEvents(object objectHasEvents) 
         { 
             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(ei.Name, 
                                                   BindingFlags.NonPublic | 
                                                   BindingFlags.Instance); 
                     if (fi != null
                     { 
                         // 将event对应的字段设置成null即可清除所有挂钩在该event上的delegate 
                         fi.SetValue(objectHasEvents, null); 
                     } 
                 } 
                 catch 
                 { 
                 } 
             } 
         }

posted on 2012-02-23 08:30  鹿我所录  阅读(545)  评论(0编辑  收藏  举报

导航