Work with event handlers in .NET.

When adding handlers indiscriminately to object events, I realized that I can attach the same handler to the event as many times as I like. This means that the handler is called once for each moment of its attachment.

It is interesting to me:

  • Is there any way to see which handlers were added to the event of the object?
  • Is it possible to remove all handlers from an event?
  • Where are these correlations between the event and its handler stored?
+3
source share
2 answers

If the event is marked with the C # event keyword , then there is no way to see subscribers from outside the object - the necessary information is simply not displayed.

, , ( ).

, , , , - .

, :

myConnection.Closing -= ConnectionClosingHandler;
myConnection.Closing += ConnectionClosingHandler;

, .
, .

, .

, :

public event PropertyChangedEventHandler Changed;

- PropertyChangedEventHandler, . , :

public event PropertyChangedEventHandler Changed
{ 
    add { ... }
    remove { ... }
}

-= += - , . Delegate MulticastDelegate ( MSDN) , .

+2

. , . :

var onclick = Click;
if (onclick != null) onclick();

Click onclick, , . , , - Click != null , .

, , :

EventHandler handler1 = (sender, e) => Console.WriteLine("test");
Click += handler1;
Click -= handler1;

, , GetInvocationList:

foreach(var handler in Click.GetInvocationList())
    Console.WriteLine(handler.Method.ToString());

, , Delegate. ( , , , ), # , , , , , Reflection , Visual Basic RemoveHandler.

+1

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


All Articles