存储要取消订阅的事件处理程序列表
我有一个带有方法 Register
的类,该方法使用标准 aClass.SomeEvent += the_handler
订阅其包含的类上的许多事件。该类还有一个 Unregister
方法,可以使用 -=
取消订阅这些事件。这工作得很好,但我们发现,如果我们添加一个新事件来订阅它,很容易忘记在 Unregister
中包含取消订阅。事实证明,这种手动维护事件订阅的方法很脆弱。
有没有办法维护可以动态迭代和取消订阅的订阅列表? (并且在Unregister
之后调用Register
时可能会迭代并重新订阅)。
一些细节:该类引用了 3 个其他类(目前但不明确限于 3 个),这些类上的各种事件都是 EventHandler
或 EventHandler
I have a class with a method, Register
that subscribes to a number of events on classes that it contains, using the standard aClass.SomeEvent += the_handler
. This class also has an Unregister
method that unsubscribes from these events using -=
. This works just fine but we're finding that if we add a new event to subscribe to that it's very easy to forget to include the unsubscription in Unregister
. This manual method of maintaining event subscriptions is proving to be fragile.
Is there a way to maintain a list of subscriptions that can be iterated over and unsubscribed from dynamically? (And potentially iterate over and re-subscribe when calling Register
after Unregister
).
Some details: The class has a reference to 3 other classes (currently, but not definitively limited to 3), the various events on these classes are all of type EventHandler
or EventHandler<T>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如何从
EventHandler.GetInspirationList()
获取调用列表,然后遍历并手动删除/取消注册它们?请注意,您只能从具有该 EventHandler 的类访问 GetInvationList() 方法,因此您可能需要公开一个方法 UnregisterAll() 以确保它删除事件调用列表中的所有延迟,您还可以确保您的类继承
IDisposable
并使用using(){ }
它将调用 Dispose 来清理所有订阅者how about getting invocation list from the
EventHandler.GetInvocationList()
and then ierate through and manually remove/unregister them ? note, you only have access to the GetInvationList() method from the class that has that EventHandler, so you might need to expose a method UnregisterAll() to make sure it removes all the delagates in the event invocation listyou can also make sure your class inherits
IDisposable
and withusing(){ }
it will call Dispose which will clean up all subscribers经过彻底查看后,我找到了这个答案:
C# Dynamic Event Subscription
这就是我想要的(几乎)。我不喜欢使用字符串来命名事件,因此我不会进一步追求这种设计。尽管这不是我想要的设计,但答案显示了一种非常有用的方法来实现所需的行为,因此我将其标记为已接受。
After a thorough look through SO I found this answer:
C# Dynamic Event Subscription
That does what I want (almost). I don't like having to name events using strings as and such I won't be pursuing this design any further. Even though it's not the design I want, the answer shows a very useful method to achieve the desired behaviour and as such I'm marking this as accepted.