存储要取消订阅的事件处理程序列表

发布于 2024-11-07 11:56:44 字数 489 浏览 0 评论 0原文

我有一个带有方法 Register 的类,该方法使用标准 aClass.SomeEvent += the_handler 订阅其包含的类上的许多事件。该类还有一个 Unregister 方法,可以使用 -= 取消订阅这些事件。这工作得很好,但我们发现,如果我们添加一个新事件来订阅它,很容易忘记在 Unregister 中包含取消订阅。事实证明,这种手动维护事件订阅的方法很脆弱。

有没有办法维护可以动态迭代和取消订阅的订阅列表? (并且在Unregister之后调用Register时可能会迭代并重新订阅)。

一些细节:该类引用了 3 个其他类(目前但不明确限于 3 个),这些类上的各种事件都是 EventHandlerEventHandler< 类型/代码>。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦魇绽荼蘼 2024-11-14 11:56:44

如何从 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 list

you can also make sure your class inherits IDisposable and with using(){ } it will call Dispose which will clean up all subscribers

苏别ゝ 2024-11-14 11:56:44

经过彻底查看后,我找到了这个答案:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文