How to remove all event handlers

Let's say we have a delegate

public delegate void MyEventHandler(string x);

and event handler

public event MyEventHandler Something;

we are adding a few events.

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

My question is: how would I remove all methods from an event handler, assuming that it does not know that it has been added 10 (or more or less) times?

+8
source share
2 answers

Just set the event to null:

this.Something = null;

Unregisters all event handlers.

+18
source

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

                }
            }
}

Using:

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

        }

    }

Using:

MyDelegate.RemoveEventHandlers();
0
source

Source: https://habr.com/ru/post/1678032/


All Articles