2010-03-05 68 views
4

我基本上要做到這一點代碼:我能有一個泛型列表類和揭露,作爲默認值

PersonList myPersonList; 
//populate myPersonList here, not shown 

Foreach (Person myPerson in myPersonList) 
{ 
... 
} 

類中聲明

public class PersonList 
{ 
public List<Person> myIntenalList; 

Person CustomFunction() 
{...} 
} 

那麼,如何揭露「 myInternalList「作爲Foreach語句可以使用的默認值嗎?或者我可以嗎?原因在於我有大約50個目前正在使用GenericCollection的類,我想遷移到泛型,但不想重寫一噸。

+0

你是什麼意思的「默認值?」 C#沒有像VB這樣的默認屬性。 – 2010-03-05 20:12:08

回答

9

你可以做PersonList實現IEnumerable<Person>

public class PersonList : IEnumerable<Person> 
{ 
    public List<Person> myIntenalList; 

    public IEnumerator<Person> GetEnumerator() 
    { 
     return this.myInternalList.GetEnumerator(); 
    } 

    Person CustomFunction() 
    {...} 
} 

或者更簡單,只要PersonList擴展列表:

public class PersonList : List<Person> 
{ 
    Person CustomFunction() { ... } 
} 

第一種方法還沒有暴露的List<T>方法的優勢,而第二是更方便,如果你想要的功能。此外,你應該使myInternalList私人。

+1

我會選擇'PersonList'實現'IEnumerable '而不是從'List '繼承的解決方案。有關更多信息,請參閱我的答案:http://stackoverflow.com/questions/2136213/c-inherit-from-dictionary-iterate-over-keyvaluepairs/2136235#2136235 – LBushkin 2010-03-05 20:23:31

5

最簡單的方法是從你的泛型列表繼承:

public class PersonList : List<Person> 
{ 
    public bool CustomMethod() 
    { 
    //... 
    } 

} 
+0

這也暴露了更改列表的方法,我不知道這是否由OP進行了indeded。如果不使用李的解決方案。 – AxelEckenberger 2010-03-05 20:18:25

+2

從.NET集合類繼承通常不是一個好主意。看到我的迴應在這裏:http://stackoverflow.com/questions/2136213/c-inherit-from-dictionary-iterate-over-keyvaluepairs/2136235#2136235。 – LBushkin 2010-03-05 20:22:31

+0

@LBushkin這只是如果他們想要覆蓋添加等,但仍然需要記住的東西。 – 2010-03-05 20:31:53

1

你爲什麼不乾脆改變PersonList基類是Collection<Person>?想必它已經可以枚舉Person,所以你的foreach仍然可以工作。

相關問題