等效

2011-12-20 189 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(); 
      } 
     } 
    } 
}