如何取消订阅泛型类的事件,该泛型类的类型参数在泛型方法中指定如下?
public class ListLayoutControl : Control
{
NotifyCollectionChangedEventHandler handler = null;
public void AttachTo<T, U>(T list) where T : INotifyCollectionChanged, ICollection<U>
{
handler = delegate (object sender, NotifyCollectionChangedEventArgs e)
{
UpdateLayout(list.Count);
};
list.CollectionChanged += handler;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// unsubscribe ??
}
base.Dispose(disposing);
}
}
答案 0 :(得分:4)
在单独的委托中捕获取消订阅并在dispose上执行:
private Action _unsubscribeHandler;
public void AttachTo<T, U>(T list) where T : INotifyCollectionChanged, ICollection<U>
{
NotifyCollectionChangedEventHandler handler = delegate (object sender, NotifyCollectionChangedEventArgs e)
{
UpdateLayout(list.Count);
};
list.CollectionChanged += handler;
_unsubscribeHandler = () => {
list.CollectionChanged -= handler;
};
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_unsubscribeHandler?.Invoke();
}
base.Dispose(disposing);
}
如果可以使用不同的列表多次调用AttachTo
- 请在List<Action>
中收集取消订阅处理程序,并在处置时执行所有操作。