gpt4 book ai didi

c# - 通过 C# 中的方法强制添加到集合的模式

转载 作者:太空狗 更新时间:2023-10-30 00:58:12 25 4
gpt4 key购买 nike

我有一个包含集合成员的类。我想阻止外部代码直接修改此集合,而是使用方法(可以执行适当的验证等)。

这比我想象的要难。这是我正在使用的解决方案。你能告诉我是否有更好的方法来做这个常见的事情吗?这一切似乎都有些过度设计。

using System.Collections.Generic;
using System.Collections.ObjectModel;
public class Foo
{
private List<Bar> _bars = new List<Bar>();

public ReadOnlyCollection<Bar> Bars { get { return _bars.AsReadOnly(); } }

public void AddBar(Bar bar) //black sheep
{
//Insert validation logic here
_bars.Add(bar);
}
}

最佳答案

我认为这是一个很好的解决方案。 Martin Fowler 在这里讨论了这种方法 Incapculate collection

关于c# - 通过 C# 中的方法强制添加到集合的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3351674/

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