c# - 拥有带有私有(private)访问器的公共(public)领域是否有意义?

标签 c# field private readonly public

我有一个类叫做 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/

相关文章:

javascript - 确定 jQuery 中对象的标签

sed - 我应该使用 cut 还是 awk 来提取字段和字段子字符串?

ios - Launcher如何获取iPhone的已安装应用程序列表?

c# - 模拟 Guid.NewGuid()

c# - 如果尚未创建,如何从 C# 以编程方式创建 MySQL 触发器?

Odoo 9 如何在表单 View 中对字段进行排序

java - 导入包会改变类的可见性吗?

带参数的 Java Reflection 私有(private)方法最好的方法?

c# - Wpf CheckedListbox - 如何获取所选项目

c# - 使用 LinQ 代码检索 bool 结果