假设我有一个 observableCollection 类:
CustomClassName testClass = new CustomClassName();
ObservableCollection<CustomClassName> collection = new ObservableCollection<CustomClassName>();
testClass.SomeEvent += OnSomeEvent;
collection.add(testClass);
当我要从集合中删除项目时,我需要手动取消订阅事件 (OnSomeEvent) 还是应该留给 GC? 退订的最佳方式是什么?
最佳答案
如果您希望收集您的元素,那么是的,您需要取消订阅。
通常的做法是:
collection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(collection_CollectionChanged);
// ...
// and add the method
void collection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
foreach (var it in e.OldItems) {
var custclass = it as CustomClassName;
if (custclass != null) custclass.SomeEvent -= OnSomeEvent;
}
}
}
关于c# - 取消订阅 observableCollection 中的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31980625/