How to remove all eventhandler

2019-04-06 06:15发布

Lets say we have a delegate

public delegate void MyEventHandler(string x);

and an event handler

public event MyEventHandler Something;

we add multiple events..

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

My question is .. how would one remove all methods from the eventhandler presuming one doesn't know its been added 10 (or more or less) times?

2条回答
够拽才男人
2楼-- · 2019-04-06 06:40

Simply set the event to null:

this.Something = null;

It will unregister all event handlers.

查看更多
相关推荐>>
3楼-- · 2019-04-06 06:42

As pseudo idea:

C#5 <

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);

                }
            }
}

Usage:

 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);

        }

    }

Usage:

MyDelegate.RemoveEventHandlers();
查看更多
登录 后发表回答