如何跟踪用户在C#中的事件? [英] How can I track subscribers to an event in C#?

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

问题描述

有一些隐藏的类属性,它将使知道吗?

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

推荐答案

如果你有机会到实际的委托(如果你使用速记事件语法,然后这是只有在实际的声明类,因为委托是私人),那么你可以叫<一href="http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx"><$c$c>GetInvocationList().

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

例如:

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天全站免登陆