如何取消订阅泛型类的事件,其类型参数在泛型方法中指定如下?
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);
}
}
最佳答案
在单独的委托(delegate)中捕获取消订阅并在处理时执行它:
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>
中收集取消订阅处理程序并在 dispose 上执行它们。
关于c# - 取消订阅其类型参数在泛型方法中指定的泛型类的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49631952/