Delete events without knowing their names

Is it possible to do this:

person.Walking -= person_Walking1; person.Walking -= person_Walking2; person.Walking -= person_Walking3; 

Do it:

 person.Walking = // remove all the handlers without knowing their names 

Thanks.

+4
source share
4 answers

Not. Part of the events is that they prevent you from doing this. If I signed up for a button click and you signed up for a button, then what right do you want to remove my handler from? (Well, this anthropomorphism is somewhat, but you get the idea.) Note that this is not a matter of knowing the "name" of the event handler - you should be able to provide a link to the "equal" instance of the delegate.

For example, if you subscribe to an event using an anonymous method or a lambda expression, you will need to reference this somewhere:

 EventHandler handler = (sender, args) => Console.WriteLine("Clicked!"); button.Click += handler; ... button.Click -= handler; 

When you use a method name that converts a group of methods from a method name to a delegate instance:

 button.Click += HandleEvent; ... button.Click -= HandleEvent; 

There are two separate delegate instances here, but they are equal because they have the same call list (they do the same) and they have the same goal (they make this thing β€œon” the same object).

EDIT: I assume that you have access to it as an event, and not as a field - if you write code in the class that publishes the event, you can do what you like and set the field to null (or delete it from the collection, or, nevertheless, your implementation).

+4
source

Of course. Just install:

 person.Walking = null; 
+2
source

This is one of the reasons why events were invented. If you want to do something like this, use delegates.

+1
source

Not outside the class in which events are defined. If you really want to, you can define a method like this:

 public void ClearEventListeners() { MyEvent.Clear(); } 

(The exact call may be different if it exists, but IntelliSense should point you in the right direction.)

0
source

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


All Articles