如何确定是否事件已经订阅 [英] How to determine if an event is already subscribed

查看:478
本文介绍了如何确定是否事件已经订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的.net应用程序,我订阅了从另一个类的事件。认购事项。我订阅事件当控制是可见的,去订阅它,当它成为无形。然而,在某些条件下,我不想脱订阅该事件,即使作为欲被发生在后台线程的动作的结果的控制是不可见的。

In my .NET application I am subscribing to events from another class. The subscription is conditional. I am subscribing to events when the control is visible and de-subscribing it when it become invisible. However, in some conditions I do not want to de-subscribe the event even if the control is not visible as I want the result of an operation which is happening on a background thread.

有没有一种方法,通过它我可以判断一类已经订阅了该事件?

Is there a way through which I can determine if a class has already subscribed to that event?

我知道我们可以在这将提高该事件通过检查事件类做,但我怎么做我做一个类,将认购该事件?

I know we can do it in the class which will raise that event by checking the event for null, but I how do I do it in a class which will subscribe to that event?

推荐答案

事件 的关键字被明确地发明了从prevent您做你想做的事。它限制访问底层代理对象,所以没有人可以直接惹的事件处理程序订阅它的商店。事件是访问的为代表,就像一个属性是一个访问一个字段。一个属性只允许获取和设置,事件只允许添加和删除。

The event keyword was explicitly invented to prevent you from doing what you want to do. It restricts access to the underlying delegate object so nobody can directly mess with the events handler subscriptions that it stores. Events are accessors for a delegate, just like a property is an accessor for a field. A property only permits get and set, an event only permits add and remove.

这使得如果知道事件处理方法和目标对象的code安全,其他code只能删除事件处理程序。 C#语言不容许您命名目标对象提出了额外的安全层的地方。

This keeps your code safe, other code can only remove an event handler if it knows the event handler method and the target object. The C# language puts an extra layer of security in place by not allowing you to name the target object.

和WinForms把安全的地方了一层额外的,所以即使你使用反射变得困难。它存储代理有一个秘密的cookie为重点,在 EventHandlerList 情况下,你必须知道cookie来挖对象淘汰之列。

And WinForms puts an extra layer of security in place so it becomes difficult even if you use Reflection. It stores delegate instances in an EventHandlerList with a secret "cookie" as the key, you'd have to know the cookie to dig the object out of the list.

好了,不要去那里。这是微不足道的解决你的问题上最终有点code:

Well, don't go there. It is trivial to solve your problem with a bit of code on your end:

private bool mSubscribed;

private void Subscribe(bool enabled)
{
    if (!enabled) textBox1.VisibleChanged -= textBox1_VisibleChanged;
    else if (!mSubscribed) textBox1.VisibleChanged += textBox1_VisibleChanged;

    mSubscribed = enabled;
}

这篇关于如何确定是否事件已经订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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