相当于类中集合的getter /setter

本文关键字:getter setter 集合 相当于 | 更新日期: 2023-09-27 18:18:36

我有一个类如下:

public class Document
{
    public List<DocumentSection> sections = new List<DocumentSection>();
    ...

各种问题涵盖了属性需要在类内部可写但在类外部只能读的情况(http://stackoverflow.com/questions/4662180/c-sharp-public-variable-as-writeable-inside-the-clas-but-readonly-outside-the-cl)

我想做同样的事情,但对于这个集合-允许从类内添加到它,但只允许用户在外部时迭代它。这是优雅可行的吗?

谢谢

相当于类中集合的getter /setter

将集合公开为IEnumerable,以便用户只能遍历它。

public class Document {
   private List<DocumentSection> sections;
   public IEnumerable<DocumentSection> Sections 
   { 
       get { return sections; }
   }
}

是的,你必须隐藏List并且只暴露Add方法和类型为IEnumerable<DocumentSection>的属性:

public class Document
{
    private List<DocumentSection> sections = new List<DocumentSection>();
    public void AddSection(DocumentSection section) {
        sections.Add(section);
    }
    public IEnumerable<DocumentSection> Sections {
        get { return sections; }
    }
}

您可以将List公开为IEnumerable<DocumentSection>,而仅在内部使用List。像这样:

public class Document {
  public IEnumerable<DocumentSection> Sections { get { return list; } }
  private List<DocumentSection> list;
}

如果您真的希望只允许迭代,您可以将illist保留为私有,但创建一个解析为GetEnumerator()的公共函数

public class Document {
   private readonly List<DocumentSection> sections = new List<DocumentSection>();
   public IEnumerable<DocumentSection> Sections 
   { 
       get 
       { 
           lock (this.sections)
           {
               return sections.ToList(); 
           }
       }
   }
}