C# Know how many EventHandlers are set?

后端 未结 3 608
生来不讨喜
生来不讨喜 2021-01-04 06:31

As we all know, we can create an EventHandler and add methods to it N number of times. Like:

   // Declare and EventHandler     
   public event EventHandler         


        
相关标签:
3条回答
  • 2021-01-04 07:10

    To find the number of event handlers, you can use this code:

    InternetConnectionAvailableEvent.GetInvocationList().Length;
    

    The following code demonstrates that MyEvent -= null does not clear the list of handlers.

    public static event EventHandler MyEvent;
    
    [STAThread]
    static void Main()
    {
       MyEvent += (s,dea) => 1.ToString();
       MyEvent -= null;
    
       Console.WriteLine(MyEvent.GetInvocationList().Length);
       // Prints 1
       MyEvent = null;
       Console.WriteLine(MyEvent == null);
       // Prints true
    }
    

    To clear the list (which is probably never a good idea), you can set the event to null (as long as you are in the class that declared the event).

    0 讨论(0)
  • 2021-01-04 07:14

    Delegates are removed by equality, so you're not removing anything from the invocation list because nothing in the invocation list would be null.

    0 讨论(0)
  • 2021-01-04 07:23

    What you are describing is a field-like event. It is the same as the longhand event declaration, except no body.

    From inside the class, you can set the event to null. From outside the class you cannot do this. Events follow a subscribe and unsubscribe methodology. Within the class you reference the variable, outside the class you reference the event.

    See this answer by Jon Skeet on events.

    0 讨论(0)
提交回复
热议问题