我可以使用具有通用列表的类并将其公开为默认值

Dil*_*789 4 c# generics

我基本上想在代码中执行此操作:

PersonList myPersonList;
//populate myPersonList here, not shown

Foreach (Person myPerson in myPersonList)
{
...
}
Run Code Online (Sandbox Code Playgroud)

类声明

public class PersonList
{
 public List<Person> myIntenalList;

 Person CustomFunction()
 {...}
}
Run Code Online (Sandbox Code Playgroud)

那么如何在我的类中公开"myInternalList"作为Foreach语句可以使用它的默认值?或者我可以吗?原因是我有大约50个当前正在使用GenericCollection的类,我想转向泛型,但不想重写.

Lee*_*Lee 9

你可以使PersonList实现 IEnumerable<Person>

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

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

    Person CustomFunction()
    {...}
}
Run Code Online (Sandbox Code Playgroud)

或者甚至更简单,只需使PersonList扩展List:

public class PersonList : List<Person>
{
    Person CustomFunction() { ... }
}
Run Code Online (Sandbox Code Playgroud)

第一种方法的优点是不暴露方法List<T>,而第二种方法如果你想要那种功能则更方便.此外,您应该将myInternalList设为私有.


C. *_*oss 5

最简单的方法是继承您的通用列表:

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

}
Run Code Online (Sandbox Code Playgroud)

  • 从.NET集合类继承通常不是一个好主意.请参阅我的回复:http://stackoverflow.com/questions/2136213/c-inherit-from-dictionary-iterate-over-keyvaluepairs/2136235#2136235. (2认同)