等效

2011-12-20 185 views
0

我有一个类如下:等效

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)

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

感谢

回答

2

揭露集合作为IEnumerable,使用户可以通过它只是迭代。

public class Document { 
    private List<DocumentSection> sections; 

    public IEnumerable<DocumentSection> Sections 
    { 
     get { return sections; } 
    } 
} 
+0

感谢Wiktor的,就像一个魅力! – Glinkot

1

是的,你要隐藏的列表,只露出一个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; } 
    } 
} 
+0

感谢那一月,非常感谢。 – Glinkot

1

,可以将该清单作为IEnumerable<DocumentSection>只有使用List内部。像这样:

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

如果你真的想只允许迭代,你可以保持与IList私人,但要公共函数解析到的GetEnumerator()

0
public class Document { 
    private readonly List<DocumentSection> sections = new List<DocumentSection>(); 

    public IEnumerable<DocumentSection> Sections 
    { 
     get 
     { 
      lock (this.sections) 
      { 
       return sections.ToList(); 
      } 
     } 
    } 
}