简体   繁体   English

如何捕获事件订阅?

[英]How to catch a subscription to event?

I have interface with the event. 我与活动有接口。 My class implements the interface. 我的课实现了接口。

The logic of the class requires to fix all the facts subscription and unsubscribe from the event. 类的逻辑要求修复所有事实订阅,并从事件中取消订阅。

How to implement interception subscriptions and unsubscribe from the event? 如何实现拦截订阅和取消订阅事件?

Try this: 尝试这个:

    private event EventHandler<EventArgs> shibby;

    public event EventHandler<EventArgs> Shibby
    {
        add
        {
            // your logic here
            this.shibby += value;
            // or here
        }
        remove
        {
            // your logic here
            this.shibby -= value;
            // or here
        }
    }

Well, if you definitely need to intercept subscriptions: 好吧,如果您确实需要拦截订阅:

private EventHandler fooEventHandler;

public event EventHandler Foo
{
    add
    {
        // Put any extra logic in here
        fooEventHandler += value;
    }
    remove
    {
        fooEventHandler -= value;
    }
}

(Note that if you need thread-safety, you'll need to amend the code above.) (请注意,如果您需要线程安全,则需要修改上面的代码。)

But if you're using a field-like event, like this: 但是,如果您使用的是类似字段的事件,则如下所示:

public event EventHandler Foo;

then you can "unsubscribe" everything just by writing (in the class): 那么您只需编写(在课堂上)即可“取消订阅”所有内容:

Foo = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM