• C#中利用反射清空事件列表


          在程序设计中有时候需要动态订阅客户自己的事件,调用完成后又要删除以前订阅的事件。因为如果不删除,有时会造成事件是会重复订阅,导致程序运行异常。一个办法是用反射来控件事件列表。清空方法代码如下:

            /// <summary>
            /// 清空控件的事件列表
            /// </summary>
            /// <param name="pControl">要清空事件列表的控件</param>
            /// <param name="pEventName">事件名</param>

            void ClearEvent(Control pControl, string pEventName)

            {

                if (pControl== null) return;

                if (string.IsNullOrEmpty(pEventName)) return;

     

                BindingFlags mPropertyFlags BindingFlags.Instance BindingFlags.Public

                    BindingFlags.Static   BindingFlags.NonPublic;//筛选

                BindingFlags mFieldFlags BindingFlags.Static BindingFlags.NonPublic;

                Type controlType typeof(System.Windows.Forms.Control);

                PropertyInfo propertyInfo controlType.GetProperty("Events", mPropertyFlags);

                EventHandlerList eventHandlerList (EventHandlerList)propertyInfo.GetValue(pControl, null);//事件列表

                FieldInfo fieldInfo (typeof(Control)).GetField("Event" pEventName, mFieldFlags);

                Delegate eventHandlerList[fieldInfo.GetValue(pControl)];

     

                if (d == null) return;

                EventInfo eventInfo=controlType.GetEvent(pEventName);

     

                foreach (Delegate dx in d.GetInvocationList())

                    eventInfo.RemoveEventHandler(pControl, dx);//移除已订阅的pEventName类型事件

     

            }

           这种方法可以一劳永逸,简单方便。但由于引入了反射,涉及到的数据类型,编译器是无法检查的,容易给程序运行时带来不稳定因素。

  • 相关阅读:
    一些易忘记的常识HTML,不定期添加
    base64 encoder/decoder for objectivec编码及解码(转)
    用XCode 开发基于网络库ACE的应用
    迅雷/旋风地址转换原理分析(转)
    主题:非常常用的Mac快捷键
    没事干测试ObjC数据类型
    These are the support and errata files for titles formerly published by Wrox Press Limited.
    iOS 开发者应该知道的 ARM 结构(转自apple4us)
    [创建型模式] Factory
    [创建型模式] Builder
  • 原文地址:https://www.cnblogs.com/RoyYu/p/2133293.html
Copyright © 2020-2023  润新知