存储一个EventHandler列表以取消订阅 [英] Store a list of EventHandlers to unsubscribe from
问题描述
我有一个类有一个方法,注册
,它使用标准的 aClass.SomeEvent来预订其包含的类上的一些事件+ = the_handler
。该类还有一个取消注册
方法,使用 - =
取消订阅这些事件。这很好,但是我们发现如果我们添加一个新的事件来订阅,那么很容易忘记在取消注册
中包含取消订阅。维护事件订阅的这种手动方法证明是脆弱的。
有没有办法维护可以迭代和取消订阅动态的订阅列表? (在取消注册
之后调用注册
可能会迭代并重新订阅。
一些细节:该类有3个其他类(目前但并非最终限于3),这些类的各种事件都是类型为$ code> EventHandler 或
EventHandler< T>
。彻底的看看,我发现这个答案:
这样做(几乎)。我不喜欢使用字符串命名事件,所以我不会再追求这个设计了。即使这不是我想要的设计,答案显示了一个非常有用的方法来实现所需的行为,因此我将其标记为接受。
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>
.
After a thorough look through SO I found this answer:
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.
这篇关于存储一个EventHandler列表以取消订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!