How to remove all eventhandler

邮差的信 提交于 2019-12-05 18:47:13

问题


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?


回答1:


Simply set the event to null:

this.Something = null;

It will unregister all event handlers.




回答2:


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


来源:https://stackoverflow.com/questions/36084469/how-to-remove-all-eventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!