取消事件所有委托方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            ProtocolEvent c = new ProtocolEvent();
            c.OnChange += new ProtocolEvent.mydelegate(c_OnChange);
            c.OnChange += new ProtocolEvent.mydelegate(c_OnChange2);

            RemoveEvent<ProtocolEvent>(c, "OnChange");

            c.OnChange += new ProtocolEvent.mydelegate(c_OnChange);

            c.Change("ddd");
        }

        static void c_OnChange(string str)
        {
            Console.WriteLine(str);
        }
        static void c_OnChange2(string str)
        {
            Console.WriteLine(str);
        }

        static void RemoveEvent<T>(T c, string name)
        {
            Delegate[] invokeList = GetObjectEventList(c, name);
            
            if (invokeList == null) return;

            foreach (Delegate del in invokeList)
            {
                typeof(T).GetEvent(name).RemoveEventHandler(c, del);
            }
        }

        /// <summary>
        /// 说来很简单,GetType().GetField("事件名",BindingFlags.Instance | BindingFlags.NonPublic);
        /// 然后调用GetValue就可以得到对应的委托了。既然有委托了。调用GetInvokeList就可以了。
        public static Delegate[] GetObjectEventList(object p_Object, string p_EventName)
        {
            FieldInfo fi = p_Object.GetType().GetField("OnChange", BindingFlags.Instance | BindingFlags.NonPublic);
            if (fi == null) return null;

            Delegate del = fi.GetValue(p_Object) as Delegate;
            if (del != null)
            {
                //执行方法
                //foreach (var item in del.GetInvocationList())
                //{
                //    Console.WriteLine(item.Method.ToString());
                //    item.Method.Invoke(null,new object[]{"str"});
                //}
                return del.GetInvocationList();
            }
            return null;
        }
    }

    class ProtocolEvent
    {
        public delegate void mydelegate(string str);

        public event mydelegate OnChange;

        public void Change(string str)
        {
            if (OnChange != null)
            {
                OnChange(str);
            }
        }
    }
}

 

posted @ 2014-07-30 17:17  s_p  阅读(385)  评论(0编辑  收藏  举报