gpt4 book ai didi

c# list property Add 方法额外 Action

转载 作者:行者123 更新时间:2023-12-03 19:15:04 26 4
gpt4 key购买 nike

我有一个这样的列表属性

protected IList<System.Windows.Media.Color> colors;    
public IList<System.Windows.Media.Color> Colors
{
get { return colors; }
set { colors = value; }
}

我有一个函数

protected void updateBuffers()

每次属性用户更改属性时都需要调用它,例如

Colors.Add(...)
...
Colors.Clear(...)

有没有一种优雅的简单方法可以做到这一点?

最佳答案

您可以使用 List 作为基类创建一个创建附加属性的新对象:

public class CustomList<T> : List<T>
{
public new void Add(T item) {
base.Add(item);
this.UpdateBuffers();
}
}

需要 'new' 关键字来完全覆盖现有的 Add 实现,它在基类中未标记为 virtual

感谢 Hans Passant 和 LarsTech 在评论中的反馈。

关于c# list property Add 方法额外 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17614254/

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