请问,
如何获得一个事件的订阅者的数量和列表?比如:this.tabControlPhone.DoubleClick += new System.EventHandler(this.tabControlPhone_DoubleClick);如果我是在代码中动态的关联tabControlPhone的DoubleClick事件和他的处理者(tabControlPhone_DoubleClick)时,我需要知道这个事件当前有没有以关联的处理者,如果有,数量多少?最好还能得到处理者的对象集合。我要根据这些信息,决定是否继续为该事件增加新的订阅者。请问,这如何编程实现?最好有例程。谢谢!

解决方案 »

  1.   


            static void Main(string[] args)
            {
                Program p = new Program();
                p.MyEvent += new EventHandler(p_MyEvent);
                p.MyEvent += new EventHandler(p_MyEvent2);
                p.MyEvent += new EventHandler(p_MyEvent3);
                EventHandler eh = p.MyEvent;
                foreach (Delegate del in eh.GetInvocationList())
                {
                    Console.WriteLine(del.Method.Name);
                }
            }        static void p_MyEvent(object sender, EventArgs e)
            {
                throw new NotImplementedException();
            }        static void p_MyEvent2(object sender, EventArgs e)
            {
                throw new NotImplementedException();
            }        static void p_MyEvent3(object sender, EventArgs e)
            {
                throw new NotImplementedException();
            }        public event EventHandler MyEvent;
      

  2.   


    谢谢!
    但是有个问题,如果这个event不是自定义事件,而是某个系统组件的预定义事件,例如以下语句,编译会报错的。EventHandler eh = this.button1.Click;Error : The event 'System.Windows.Forms.Control.Click' can only appear on the left hand side of += or -= 这该如何解决阿??
      

  3.   


            static void Main(string[] args)
            {
                System.Windows.Forms.Button btn = new System.Windows.Forms.Button();
                btn.Click += new EventHandler(btn_Click);
                btn.Click += new EventHandler(btn_Click2);
                btn.Click += new EventHandler(btn_Click3);
                PropertyInfo pi = btn.GetType().GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
                EventHandlerList ehl = (EventHandlerList)pi.GetValue(btn, null);
                FieldInfo fieldInfo = (typeof(System.Windows.Forms.Control)).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
                Delegate d = ehl[fieldInfo.GetValue(null)];
                foreach (Delegate del in d.GetInvocationList())
                    Console.WriteLine(del.Method.Name);
            }        static void btn_Click(object sender, EventArgs e)
            {
                Console.WriteLine("Click1");
            }        static void btn_Click2(object sender, EventArgs e)
            {
                Console.WriteLine("Click2");
            }        static void btn_Click3(object sender, EventArgs e)
            {
                Console.WriteLine("Click3");
            }