Can I get a class with a general list and show that as the default value

Basically I want to do this in code:

PersonList myPersonList; //populate myPersonList here, not shown Foreach (Person myPerson in myPersonList) { ... } 

Class declares

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

So, how do I show "myInternalList" in my class as the default value that the Foreach operator can use? Or can I? The reason is because I have about 50 classes that currently use GenericCollection, which I would like to move to generics, but don't want to rewrite a ton.

+4
source share
3 answers

You can make an implementation of PersonList IEnumerable<Person>

 public class PersonList : IEnumerable<Person> { public List<Person> myIntenalList; public IEnumerator<Person> GetEnumerator() { return this.myInternalList.GetEnumerator(); } Person CustomFunction() {...} } 

Or even simpler, just add a PersonList to the List:

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

The first method has the advantage of not exposing List<T> methods, and the second is more convenient if you want this functionality. In addition, you must make myInternalList private.

+9
source

The easiest way is to inherit from your shared list:

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

Why don't you just change the base class from PersonList to Collection<Person> ? It is clear that it can already list Person, so your foreach will still work.

+1
source

Source: https://habr.com/ru/post/1303290/


All Articles