开发者

How to catch a subscription to event?

开发者 https://www.devze.com 2023-01-18 18:02 出处:网络
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.

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号