Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我可以拥有一个具有泛型列表的类并将其作为默认值公开吗_C#_Generics - Fatal编程技术网

C# 我可以拥有一个具有泛型列表的类并将其作为默认值公开吗

C# 我可以拥有一个具有泛型列表的类并将其作为默认值公开吗,c#,generics,C#,Generics,我基本上想在代码中这样做: PersonList myPersonList; //populate myPersonList here, not shown Foreach (Person myPerson in myPersonList) { ... } 类声明 public class PersonList { public List<Person> myIntenalList; Person CustomFunction() {...} } 公共类个人列表 { 公

我基本上想在代码中这样做:

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,我想将它们转移到泛型,但不想重新编写一吨。最简单的方法是从泛型列表继承:

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

}
公共类个人列表:列表
{
公共bool CustomMethod()
{ 
//...
}
}

为什么不简单地将PersonList上的基类更改为
Collection
?很可能它已经在Person上枚举了,所以您的foreach仍然可以工作。

您可以让PersonList实现
IEnumerable

公共类PersonList:IEnumerable
{
公开名单;
公共IEnumerator GetEnumerator()
{
返回此.myInternalList.GetEnumerator();
}
人员自定义功能()
{...}
}
或者更简单,只需使PersonList扩展列表:

public class PersonList : List<Person>
{
    Person CustomFunction() { ... }
}
公共类个人列表:列表
{
Person CustomFunction(){…}
}

第一种方法的优点是不公开
List
的方法,而第二种方法更方便,如果您需要该功能的话。另外,您应该将myInternalList设置为私有。

什么是“默认值?”C#没有VB之类的默认属性。这也暴露了更改列表的方法,我不知道这是否由OP确定。如果不使用Lee的解决方案,则从.NET集合类继承通常不是一个好主意。请看我的回答:.@LBushkin这只有在他们想要覆盖add等时才有必要。但还是要记住一些好的东西。我会选择让
PersonList
实现
IEnumerable
的解决方案,而不是从
列表继承。更多信息,请参见我的回答:
public class PersonList : List<Person>
{
    Person CustomFunction() { ... }
}