如何跟踪C#中的活动订阅者? [英] How can I track subscribers to an event in C#?

查看:110
本文介绍了如何跟踪C#中的活动订阅者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

如果您有权访问实际的代理(如果您使用简写事件语法,那么这只是在实际的声明类中,因为委托是 private ),那么您可以致电 GetInvocationList( )



例如:

 code> public event EventHandler MyEvent; 

要获取订阅者列表,您可以拨打:

  Delegate [] subscribers = MyEvent.GetInvocationList(); 

然后,您可以检查方法 Target 订阅者的每个元素的属性数组,如有必要。



这样做的原因是因为我们上面发现的事件实际上是类似于



  private EventHandler myEventDelegate; 

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

这就是为什么当从声明类中查看时,事件看起来不同到其他任何地方(包括从它继承的类)。唯一的面向公众的界面是添加删除功能;实际的代表,即保留订阅的是 private


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

解决方案

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.

这篇关于如何跟踪C#中的活动订阅者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆