C# Event Handlers

前端 未结 4 1210
Happy的楠姐
Happy的楠姐 2021-01-17 23:32

How can I check in C# if button.Click event has any handlers associated? If (button.Click != null) throws compile error.

相关标签:
4条回答
  • 2021-01-17 23:38

    You can't. Events just expose "add a handler" and "remove a handler" - that's all. (In fact in the CLR you can also have metadata to associate a method with "fire the event" but the C# compiler never generates that.) Some event publishers may offer additional means to check whether or not there are any subscribers (or indeed let you see those subscribers) but it's not part of the event pattern itself.

    See my article about events for more information, or look at the events tag (which I'm about to add to this question).

    0 讨论(0)
  • 2021-01-17 23:38

    Why do you need this? What is the context? Maybe there's a better way to achieve the result
    The button is an external object and what you're trying to do is check is its internal list of subscribers without asking it. It's violating encapsulation..
    You should always let the object manage the subscribers for the events it exposes. If it wanted clients to be aware, it would have exposed a method HasClientsRegistered. Don't break in.

    0 讨论(0)
  • 2021-01-17 23:43

    EventDescriptor e = TypeDescriptor.GetEvents(yourObject).Find("yourEventName", true);

    0 讨论(0)
  • 2021-01-17 23:48

    I think you can if you are in the class that raises the event.

    You can define the handler and enumerate each.

    e.g. If your event is defined as

    event System.EventHandler NewEvent;
    

    Then on the raise event method you might create you can do...

        EventHandler handler = NewEvent;
        if(handler != null)
        {
          handler(this, e);
        }
    

    That will give you the handler and from that you can get the Invocation List.

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