C#如何找到如果事件被钩 [英] C# How to find if an event is hooked up

查看:163
本文介绍了C#如何找到如果事件被钩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够找出如果事件被钩与否。我环顾四周,但我只发现涉及修改包含该事件的对象的内部解决方案。我不想这样做。

I want to be able to find out if an event is hooked up or not. I've looked around, but I've only found solutions that involved modifying the internals of the object that contains the event. I don't want to do this.

下面是一些测试code,我认为会的工作:

Here is some test code that I thought would work:

// Create a new event handler that takes in the function I want to execute when the event fires
EventHandler myEventHandler = new EventHandler(myObject_SomeEvent);
// Get "p1" number events that got hooked up to myEventHandler
int p1 = myEventHandler.GetInvocationList().Length;
// Now actually hook an event up
myObject.SomeEvent += m_myEventHandler;
// Re check "p2" number of events hooked up to myEventHandler
int p2 = myEventHandler.GetInvocationList().Length;

Unfort上面是完全错误的。我认为,当我迷上一个事件,它不知何故在一个MyEventHandlerinvocationList会自动得到更新。但是,没有,这是情况并非如此。这样做的长度总是回来为一体。

Unfort the above is dead wrong. I thought that somehow the "invocationList" in myEventHandler would automatically get updated when I hooked an event to it. But no, this is not the case. The length of this always comes back as one.

反正从包含该事件的对象之外的确定这?

Is there anyway to determine this from outside the object that contains the event?

推荐答案

有是由C#事件关键字psented一个微妙的错觉$ P $,那就是一个事件有一个调用列表。

There is a subtle illusion presented by the C# event keyword and that is that an event has an invocation list.

如果你声明使用C#事件关键字时,编译器将生成类的私人代表,并管理它。每当你订阅的情况下,编译器生成的添加方法被调用,其中追加事件处理程序委托的调用列表。目前该事件没有明确的调用列表。

If you declare the event using the C# event keyword, the compiler will generate a private delegate in your class, and manage it for you. Whenever you subscribe to the event, the compiler-generated add method is invoked, which appends the event handler to the delegate's invocation list. There is no explicit invocation list for the event.

因此​​,为了获得在委托的调用列表中的唯一方法是preferably:

Thus, the only way to get at the delegate's invocation list is to preferably:


  • 使用反射来访问编译器生成的委托或

  • 创建一个非私有委托(可能是内部),并实现事件的add /手动删除方法(这$ P $从生成事件的默认实现pvents编译)

下面是一个例子证明了后者的技术。

Here is an example demonstrating the latter technique.

class MyType
{
    internal EventHandler<int> _delegate;
    public event EventHandler<int> MyEvent;
    {
        add { _delegate += value; }
        remove { _delegate -= value; }
    }
}

这篇关于C#如何找到如果事件被钩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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