我有一个模型类,其中包含我从其他类订阅的事件。我想正确订阅和取消订阅每个类(class)。
- 首先,我想保证在 MyClass 中我只取消订阅一次,即使代码在少数方法中也是如此。
其次,除了 MyClass 之外,还有其他类使用 OnMyEvent,所以我不想无意中取消订阅类(class)中的事件。
MyClass(IModel model) { _model = model; _model.OnMyEvent +=EventHandle; } Close() { _model.OnMyEvent -=EventHandle; } Disconnect() { //I want to check if OnMyEvent has already unsibscribed //Moreover OnMyEvent is used in other classes and //I don't want to mess up with it here _model.OnMyEvent -=EventHandle; }
最佳答案
如果您只订阅一次,那么您取消订阅多少次并不重要 - 在您没有订阅的情况下取消订阅是无操作的。同样,事件 API 的全部意义在于您不能不小心取消订阅其他订阅(其他类型或相同类型的其他实例)。
因此,所示代码应该没问题,尽管将这两个调用移至处理此问题的单个方法可能是值得的。不过,这可能有点矫枉过正。
此外,如果您的类型是 IDisposable
,请确保它也在该代码路径中被调用(大概是通过调用 Close()
)。
关于c# - 在 C# 中取消订阅事件的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6436396/