【问题标题】:Equivalent of getters/setters for collections within a class类中集合的 getter/setter 等价物
【发布时间】:2012-01-24 09:37:52
【问题描述】:
我有一堂课如下:
public class Document
{
public List<DocumentSection> sections = new List<DocumentSection>();
...
各种问题涵盖属性需要在类内部可写但从外部只读的情况(http://stackoverflow.com/questions/4662180/c-sharp-public-变量-as-writeable-inside-the-clas-but-readonly-outside-the-cl)
我想对这个集合做同样的事情 - 允许从类内添加到它,但只允许用户在它外面时迭代它。这优雅可行吗?
谢谢
【问题讨论】:
标签:
c#
scope
encapsulation
【解决方案1】:
将集合公开为IEnumerable,以便用户只能遍历它。
public class Document {
private List<DocumentSection> sections;
public IEnumerable<DocumentSection> Sections
{
get { return sections; }
}
}
【解决方案2】:
是的,您必须隐藏 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; }
}
}
【解决方案3】:
您可以将列表公开为IEnumerable<DocumentSection>,并且仅在内部使用List。像这样:
public class Document {
public IEnumerable<DocumentSection> Sections { get { return list; } }
private List<DocumentSection> list;
}
【解决方案4】:
如果你真的想只允许迭代,你可以保持 IList 私有,但创建一个解析为 GetEnumerator() 的公共函数
【解决方案5】:
public class Document {
private readonly List<DocumentSection> sections = new List<DocumentSection>();
public IEnumerable<DocumentSection> Sections
{
get
{
lock (this.sections)
{
return sections.ToList();
}
}
}
}