2010-03-05 45 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仍然可以工作。

相关问题