存储事件处理器取消订阅列表 [英] Store a list of EventHandlers to unsubscribe from

查看:104
本文介绍了存储事件处理器取消订阅列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法的类,订阅了有关它包含的类了一系列活动,使用标准的注册 aClass.SomeEvent + = the_handler 。这个类也有使用从这些事件中的退订注销法 - = 。这工作得很好,但我们发现,如果我们添加一个新的事件订阅,它很容易忘记,包括注销取消订阅。本手册维护事件订阅的方法被证明是脆弱的。

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).

一些细节:类有其他3类(目前,但不明确限于3),这些类的各种事件都是类型的引用事件处理程序事件处理程序< T>

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>.

推荐答案

在一个彻底看通过SO,我发现这样的回答:

After a thorough look through SO I found this answer:

C#动态事件订阅

这是我想要做什么(几乎)。我不喜欢使用字符串作为和这样我不会任何进一步的追求这样的设计不得不名事件。即使它不是我想要的设计,答案显示了一个非常有用的方法来实现所期望的行为,因此,我标记此作为接受

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.

这篇关于存储事件处理器取消订阅列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆