简体   繁体   中英

How can I clear subscriptions from one particular event handler in C#?

I've been been studying event systems in C#, so I do understand why you can't directly access the subscribers of an event. (I started with delegates, went through anonymous functions and lambda statements). I then came upon the problem of managing the subscriptions when implementing my first system. I am VERY green here.

As usual Stackoverflow is very helpful. This question shows me how to make a function to clear all the subscribers. For my purposes, this will be specific enough (clear all and assign new as desired).

How might I inform a single function to clear one of several event delegates?

public delegate void AnEventHandler(object sender, EventArgs e);

public class EventPublisher :
{
    public event AnEventHandler GroupA;
    public event AnEventHandler GroupB;

    public void ClearSubscribers(AnEventHandler handlerToClear)
    {
        handlerToClear = null;
    }
}

I thought I could write it like this, and my subscribing class could simply do

(EventPublisher MyPublisher)

MyPublisher.ClearSubscribers(MyPublisher.GroupA);

But alas it informs I can only use that with the += or -= operator, which surprised me a bit because I thought a reference would be acceptable.

I also do intend to implement my own add() and remove() functions. The thing about that is, it has the same problem: I need 6 event handlers. Surely I don't need to write 6 parallel nullification function and 6 unique pairs of add/remove functions? My brain is thinking inheritance but dots aren't connecting.

If you can afford to, setting a variable to null will remove it's variables, then just re-set it.

Otherwise you should be able to do it this way .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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