[英]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. 我一直在研究事件系统在C#中,所以我不明白你为什么不能直接访问事件的用户。 (I started with delegates, went through anonymous functions and lambda statements). (我从代表开始,经历了匿名函数和lambda语句)。 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. 和往常一样,Stackoverflow非常有帮助。 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) (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. 我也打算实现自己的add()和remove()函数。 The thing about that is, it has the same problem: I need 6 event handlers. 关于它的问题是,它具有相同的问题:我需要6个事件处理程序。 Surely I don't need to write 6 parallel nullification function and 6 unique pairs of add/remove functions? 当然,我不需要编写6个并行无效函数和6对唯一的添加/删除函数对吗? My brain is thinking inheritance but dots aren't connecting. 我的大脑在思考继承,但点之间没有联系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.