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

你说的曾经没有我的故事 提交于 2019-12-12 07:47:10

问题


Is there some hidden class property which would allow to know this ?


回答1:


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.



来源:https://stackoverflow.com/questions/4911009/how-can-i-track-subscribers-to-an-event-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!