我有一个带有集合成员的类。我想防止外部代码直接修改这个集合,而不是使用方法(可以执行适当的验证等)。
这比我想象的要难。这是我正在使用的解决方案。你能告诉我是否有更好的方法来做这个常见的事情吗?这一切似乎有点过度设计。
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);
}
}