gpt4 book ai didi

c# - 是否有将通用集合公开为只读的良好模式?

转载 作者:太空狗 更新时间:2023-10-29 21:42:01 24 4
gpt4 key购买 nike

所以我得到了这些公开子对象集合的类。

我不希望其他类在集合中添加或删除对象,因为我需要连接到子对象中的事件,因此当它们被添加或删除时,我希望能够进行额外的处理。但我真的很喜欢在内部轻松操作泛型。

我有没有提到这是一个 WPF 应用程序,所以我需要 INotifySupport?

我能想到的最好的就是这样。

public class foo : INotifyPropertyChanged
{
protected List<ChildFoo> _Children = new List<ChildFoo>();

public foo()
{
}

public void AddChild(ChildFoo newChild)
{
DoAttachLogic(newChild);
_Children.Add(newChild);
NotifyPropertyChange("Children");
}

public void RemoveChild(ChildFoo oldChild)
{
DoRemoveLogic(oldChild);
_Children.Remove(oldChild);
NotifyPropertyChange("Children");
}

public ChildFoo[] Children
{
get
{
return _Children.ToArray();
}
}

}

此设计是否存在我没​​有发现的严重缺陷?

每次访问 Children 属性时,我们都会产生将列表转换为数组的开销。

对此有任何建议都很好。

最佳答案

这是我对普通代码所做的:

Public Readonly Property Childern As ObjectModel.ReadOnlyCollection(Of Child)
Get
Return New ObjectModel.ReadOnlyCollection(Of Child)(_ChildernList)
End Get
End Property

对于 WPF 代码,我只公开 ObservableCollection 的一个子类。

关于c# - 是否有将通用集合公开为只读的良好模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3894381/

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