![](/img/trans.png)
[英]Distinguish between a class generic type parameter and method generic type parameter
[英]Unsubscribe from an event of a generic class whose type parameter is specified within a generic method
如何取消订阅泛型类的事件,该泛型类的类型参数在泛型方法中指定如下?
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);
}
}
捕获单独委托中的取消订阅并在处置时执行:
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上执行所有操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.