![](/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.