2009-05-20 49 views
3

我在想在處理集合時使用屬性的最佳方式是什麼。在處理集合時正確使用屬性

例如我有一個Foo類,我想要一個存儲該類的列表。以下哪項應使用:

private List<Foo> myList; 
private List<Foo> myOtherList = new List<Foo>(); 

現在的屬性:

public List<Foo> ListOfFoo 
    { 
    get 
    { 
     return myList; 
    } 
    set 
    { 
     myList= new List<Foo>(value); 
    } 
    } 

還是應該設定只是以價值?

public List<Foo> ListOfFoo 
    { 
    get 
    { 
     return myList; 
    } 
    set 
    { 
     myList= value; 
    } 
    } 
+0

什麼原因可以從外部設置收集? – peterchen 2009-05-20 13:45:44

+0

該屬性正在進行自定義控件,該控件允許僅爲列表中的Foo對象拖放功能。我打算查詢數據庫以獲取對象列表。每個控件可以有相同或不同的列表。 – Billy 2009-05-20 14:17:48

回答

2

選擇

private List<Foo> myOtherList = new List<Foo>(); 

becuse另一隻聲明瞭一個參考(其被設置爲空),上面的示例聲明到列表的引用,創建一個列表和該assignes新列表到參考。

選擇

public List<Foo> ListOfFoo 
    { 
    get { return myList; } 
    set { myList= new List<Foo>(value); } 
    } 

當你想myList中爲NOT refelect它被分配給myList中如後發生在列表中的任何改變

List<string> myFirstList = new List<string>(); 
myFirstList.Add("Hello"); 
myFirstList.Add("World"); 

List<string> mySecondList = new List<string>(myFirstList); 
// mySecondList now contains Hello & world 

myFirstList.Add("Boyo"); 
// myFrist List now contains Hello, world & Boyo 
// mySecondList still contains Hello & world 

選擇

public List<Foo> ListOfFoo 
    { 
    get { return myList; } 
    set { myList= value; } 
    } 

當你想兩個引用指向同一個對象如

List<string> myFirstList = new List<string>(); 
myFirstList.Add("Hello"); 
myFirstList.Add("World"); 

List<string> mySecondList = myFirstList; 
// mySecondList now contains Hello & world 

myFirstList.Add("Boyo"); 
// myFrist List now contains Hello, world & Boyo 
// mySecondList "also" contains Hello, world & Boyo 

的「也」以上是引號,因爲實際上,只有一個列表,我的兩個第一和第二點,以相同的列表。

0

這取決於。

使用第一種樣式時,將創建列表的副本,這通常是不必要的。 .Net約定是爲設置者分配對該屬性的引用。這就是爲什麼我會傾向於第二種選擇。

但是,如果您打算進行復制操作,第一個選項就是您要查找的內容。

2

一般來說,你不希望使用豐富類型的屬性,如List<T>(通常人們會用Collection<T>),一般的集合類型的屬性是隻讀的 - 集合本身能夠像Clear方法修改, Add等,這通常是足夠的。

例如:

class Foo 
{ 
    Collection<Bar> _bars = new Collection<Bar>(); 

    public Collection<Bar> Bars { get { return _bars; } } 
} 

這也讓你打開通過實施Collection<T>後裔和重寫InsertItemSetItem等方法來驗證修改集合。

0

一般情況下,只露出一個接口(ICollection的,IList的或類似),並使其只讀:

private IList<Foo> m_list = new List<Foo>(); 
public IList<Foo> List {get { return m_list; } } 

優點:可以修改的實施,例如從列表切換到可觀察列表。您可能需要製作具體類型的m_list成員,而不是界面,例如使用額外的功能。

有了可設置的外部列表,您遇到了一些問題。然而,也有一些情況下,這是需要:

  • 數據可以從外部產生,並且是潛在的大,變化頻繁(如幾萬項)
  • 外部列表之間應共享不同的實例
0

爲什麼不在類上使用IEnumerator接口,如果您必須使用setter,請使用某種方法。

這樣你也隱藏了實際的List-Implementation。

class FooBar : IEnumerator 
{ 
    private Collection<Foo> col; 

    public IEnumarator GetEnumerator() 
    { 
    return col.GetEnumerator(); 
    } 

    public void SetList(Collection col) 
    { 
    this.col= col; // you can also make this more general and convert the parameter so it fits your listimpl. 
    } 
} 

class Clazz 
{ 
    private void WhatEver(){ 
    FooBar foobar = new FooBar(); 
    ... 
    foreach(Foo f in foobar) 
    {...} 
    } 
}