我基本上想在代码中执行此操作:
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的类,我想转向泛型,但不想重写.
你可以使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设为私有.
最简单的方法是继承您的通用列表:
public class PersonList : List<Person>
{
public bool CustomMethod()
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
244 次 |
最近记录: |