开发者

How can I track subscribers to an event in C#?

开发者 https://www.devze.com 2023-02-08 14:55 出处:网络
Is there some hidden class property which would allow to know th开发者_运维百科is ?If you have access to the actual delegate (if you\'re using the shorthand event syntax, then this is only within the

Is there some hidden class property which would allow to know th开发者_运维百科is ?


If you have access to the actual delegate (if you're using the shorthand event syntax, then this is only within the actual declaring class, as the delegate is private), then you can call GetInvocationList().

For instance:

public event EventHandler MyEvent;

To get the list of subscribers, you can call:

Delegate[] subscribers = MyEvent.GetInvocationList();

You can then inspect the Method and Target properties of each element of the subscribers array, if necessary.

The reason this works is because declaring the event as we did above actually does something akin to this:

private EventHandler myEventDelegate;

public event EventHandler MyEvent
{
    add { myEventDelegate += value; }
    remove { myEventDelegate -= value; }
}

This is why the event looks different when viewed from within the declaring class compared to anywhere else (including classes that inherit from it). The only public-facing interface is the add and remove functionality; the actual delegate, which is what holds the subscriptions, is private.

0

精彩评论

暂无评论...
验证码 换一张
取 消