如何在C#中我可以明确的事件订阅? [英] How can I clear event subscriptions in C#?

查看:82
本文介绍了如何在C#中我可以明确的事件订阅?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看下面的C#类:

c1 {
 event EventHandler someEvent;
}

如果有很多订阅到 C1 someEvent 事件,我想清除它们所有,什么是实现这一目标的最佳途径? 同时考虑订阅此事件可能是/是lambda表达式/匿名委托。

If there are a lot of subscriptions to c1's someEvent event and I want to clear them all, what is the best way to achieve this? Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.

目前我的解决办法是增加一个 ResetSubscriptions()方法 C1 ,设置 someEvent 为null。我不知道这有什么看不见的后果。

Currently my solution is to add a ResetSubscriptions() method to c1 that sets someEvent to null. I don't know if this has any unseen consequences.

推荐答案

在类中,你可以设置(隐藏)变量设置为null。空引用是再$ P $的正规途径psenting一个空的调用列表,有效。

From within the class, you can set the (hidden) variable to null. A null reference is the canonical way of representing an empty invocation list, effectively.

从类之外,你不能做到这一点 - 活动基本上暴露订阅及取消订阅,就是这样

From outside the class, you can't do this - events basically expose "subscribe" and "unsubscribe" and that's it.

这是值得意识到了什么字段的事件实际上是做 - 他们创造一个变量的的事件在同一时间。在类,你最终引用变量。从外面,你引用的事件。

It's worth being aware of what field-like events are actually doing - they're creating a variable and an event at the same time. Within the class, you end up referencing the variable. From outside, you reference the event.

参见事件和委托我本文的详细信息。

See my article on events and delegates for more information.

这篇关于如何在C#中我可以明确的事件订阅?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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