您的位置:首页 > 编程语言 > C#

ArcEngine利用C#反射获取事件列表

2012-08-13 20:47 267 查看
转自:http://www.cnblogs.com/caodajieup/archive/2011/09/29/2195117.html

 

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

       
/// <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 d = eventHandlerList[fieldInfo.GetValue(pControl)];

 

            if (d == null) return;

            EventInfo eventInfo=controlType.GetEvent(pEventName);

 

            foreach (Delegate dx in d.GetInvocationList())

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

 

        }

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

 

以上转载的,我是要用来判断ArcEngine中PageLayoutControl控件的事件是否绑定处理函数的,由于MS事件机制的修改,已经不能通过==null的方式来判断事件是否绑定函数了,需要用到反射,这个例子虽然短,不过刚好能说明情况

 
Type t = typeof(AxPageLayoutControl);

            System.Reflection.FieldInfo fieldInfo = t.GetField("OnDoubleClick", myBindingFlags);

            Delegate instanceDelegate = fieldInfo.GetValue(axPageLayoutControl1) as Delegate;

            string msg = "";

            if (instanceDelegate != null)

            {

                foreach (Delegate d in instanceDelegate.GetInvocationList())

                {

                    //c.OnChange -= d as EventHandler;

                    ////evt.RemoveEventHandler(c, d as EventHandler);

                    msg += d.Method.Name;

                }

            }

            MessageBox.Show("deligate is:" + msg);

这样就能把PageLayoutControl的OnDoubleClick绑定的所有函数的名称输出出来

可以进一步修改
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# null events 编译器 string c