如何删除所有eventhandler

时间:2016-03-18 12:30:22

标签: c# delegates event-handling

假设我们有一名代表

public delegate void MyEventHandler(string x);

和一个事件处理程序

public event MyEventHandler Something;

我们添加了多个事件..

for(int x = 0; x <10; x++)  
{
   this.Something += HandleSomething;
}

我的问题是..如何从事件处理程序中删除所有方法,假设一个人不知道它被添加了10次(或更多或更少)次?

2 个答案:

答案 0 :(得分:20)

只需将活动设置为null

即可
this.Something = null;

它将取消注册所有事件处理程序。

答案 1 :(得分:0)

作为伪想法:

C#5&lt;

class MyDelegateHelperClass{
    public static void RemoveEventHandlers<TModel, TItem>(MulticastDelegate m, Expression<Func<TModel, TItem>> expr) {


                EventInfo eventInfo= ((MemberExpression)expr.Body).Member as EventInfo;


                Delegate[] subscribers = m.GetInvocationList();

                Delegate currentDelegate;

                for (int i = 0; i < subscribers.Length; i++) {

                    currentDelegate=subscribers[i];
                    eventInfo.RemoveEventHandler(currentDelegate.Target,currentDelegate);

                }
            }
}

用法:

 MyDelegateHelperClass.RemoveEventHandlers(MyDelegate,()=>myClass.myDelegate);

C#6

public static void RemoveEventHandlers(this MulticastDelegate m){

        string eventName=nameof(m);

        EventInfo eventInfo=m.GetType().ReflectingType.GetEvent(eventName,BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);


        Delegate[] subscribers = m.GetInvocationList();

        Delegate currentDelegate;

        for (int i = 0; i < subscribers.Length; i++) {

            currentDelegate=subscribers[i];
            eventInfo.RemoveEventHandler(currentDelegate.Target,currentDelegate);

        }

    }

用法:

MyDelegate.RemoveEventHandlers();