zoukankan      html  css  js  c++  java
  • 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;
            
  • 相关阅读:
    jQuery插件开发之定宽输出
    全国所有省市县地理坐标Json格式
    diff/merge configuration in TFS
    How to accelerate your VPC 2007
    TechNet Magazine/TechNet杂志
    net helpmsg get error message for error id in cmd script
    devenv.exe /DebugExe debug unitcase
    ZoomIt for demo
    diskpart to deal with driver letter changed after reboot in Virtual Machine
    几个关于web开发资源的站点
  • 原文地址:https://www.cnblogs.com/as3lib/p/6443047.html
Copyright © 2011-2022 走看看