简体   繁体   中英

C# Event Handlers

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

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

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.

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

You can define the handler and enumerate each.

eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM