我有一个类叫做 GestorePersonale
它包含另一个类的实例列表:
public List<Dipendente> Dipendenti { get; private set; }
我想让这个列表只能通过类公开的方法修改,而不是直接修改。我注意到使用上面的代码,可以做到
var gp = new GestorePersonale(); gp.Dipendenti.Add( new Dipendente( ... ) );并能够对
List<Dipendente>
执行任何其他类型的操作本身。
我考虑过将第一个代码片段转换为
private List dipendenti;
但我可以找到一些缺点:
- 这会打破我的个人规则,即尽可能在类的方法内部尝试始终使用公共(public)字段而不是私有(private)字段(尽管我不确定这样做是否是好的做法,因此欢迎任何澄清);
- 这会损害任何外部实体访问列表内容的能力,仅用于阅读目的,例如,执行 LINQ查询列表的内容。
解决这种情况的最佳方法是什么?
最佳答案
您可以将列表包装在 ReadOnlyCollection<T> 中并公开:
private List<Dipendente> dipendenti;
private ReadOnlyCollection<Dipendente> readOnlyDipendenti;
public GestorePersonale()
{
dipendenti = new List<Dipendente>();
readOnlyDipendenti = new ReadOnlyCollection<Dipendente>(dipendenti);
}
public ReadOnlyCollection<Dipendente> Dipendenti
{
get { return readOnlyDipendenti; }
}
在内部,您可以访问 dipendenti
并可以添加/删除项目。外部实体只能访问包装列表的 ReadOnlyCollection
关于c# - 拥有带有私有(private)访问器的公共(public)领域是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9201372/