gpt4 book ai didi

c# - 取消订阅其类型参数在泛型方法中指定的泛型类的事件

转载 作者:太空狗 更新时间:2023-10-30 01:13:33 24 4
gpt4 key购买 nike

如何取消订阅泛型类的事件,其类型参数在泛型方法中指定如下?

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com