取消订阅observableCollection中的事件

时间:2015-08-13 06:07:20

标签: c#

假设我有一个observableCollection类:

CustomClassName testClass = new CustomClassName();
ObservableCollection<CustomClassName> collection = new ObservableCollection<CustomClassName>();
testClass.SomeEvent += OnSomeEvent;
collection.add(testClass);

当我要从集合中删除项目时,我是否需要手动取消订阅事件(OnSomeEvent),还是应该将其留给GC? 什么是取消订阅的最佳方式?

1 个答案:

答案 0 :(得分:5)

如果您希望收集您的商品,那么您需要取消订阅。

为此,通常的方法是:

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;
        }
    }
}