c#通过反射移除所有事件

移除全部事件委托

C# code
 

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 public class Test
    {
        public event EventHandler AA;
        public void Foo()
        {
            if (AA != null) AA(thisnew EventArgs());
        }
    }
 
static void Main(string[] args)
        {
            Test obj = new Test(); 
            obj.AA += delegate { Console.WriteLine("event raised."); }; 
            obj.Foo(); 
            RemoveEvent<Test>(obj, "AA"); 
            obj.Foo(); 
            Console.ReadKey();
        }
 
        static void RemoveEvent<T>(T c, string name)
        {
            Delegate[] invokeList = GetObjectEventList(c, "AA"); 
            foreach (Delegate del in invokeList) 
            
                typeof(T).GetEvent("AA").RemoveEventHandler(c, del); 
            }
        }
  
        ///  <summary>     
        /// 获取对象事件 zgke@sina.com qq:116149     
        ///  </summary>     
        ///  <param name="p_Object">对象 </param>     
        ///  <param name="p_EventName">事件名 </param>     
        ///  <returns>委托列 </returns>     
        public static Delegate[] GetObjectEventList(object p_Object, string p_EventName)
        {
            FieldInfo _Field = p_Object.GetType().GetField(p_EventName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
            if (_Field == null
            
                return null;
            
            object _FieldValue = _Field.GetValue(p_Object); 
            if (_FieldValue != null && _FieldValue is Delegate) 
            
                Delegate _ObjectDelegate = (Delegate)_FieldValue; 
                return _ObjectDelegate.GetInvocationList();
            
            return null;
        
上一篇:SVN 图标不显示的解决办法


下一篇:Windows下安装Redmine-2.5.3