In C #, how can I create an IEnumerable <T> class with various types of objects>

In C #, how can I create an IEnumerable<T> class with various types of objects

For instance:

 Public class Animals { Public class dog{} Public class cat{} Public class sheep{} } 

I want to do something like:

 Foreach(var animal in Animals) { Print animal.nameType } 
+6
source share
3 answers

another approach if you need a named collection (instead of using a List<T> ):

 // animal classes public class Animal { public String Name { get; set; } public Animal() : this("Unknown") {} public Animal(String name) { this.Name = name; } } public class Dog : Animal { public Dog() { this.Name = "Dog"; } } public class Cat : Animal { public Cat() { this.Name = "Cat"; } } // animal collection public class Animals : Collection<Animal> { } 

Implementation:

 void Main() { // establish a list of animals and populate it Animals animals = new Animals(); animals.Add(new Animal()); animals.Add(new Dog()); animals.Add(new Cat()); animals.Add(new Animal("Cheetah")); // iterate over these animals foreach (var animal in animals) { Console.WriteLine(animal.Name); } } 

Here you set aside the foundation of Collection<T> , which implements IEnumerable<T> (so foreach and other iteration methods work with it).

+1
source
 public class Animal { } public class Dog : Animal { } public class Cat : Animal { } List<Animal> animals = new List<Animal>(); animals.Add(new Dog()); animals.Add(new Cat()); 

Then you can iterate over the collection with:

 foreach (var animal in animals) { Console.WriteLine(animal.GetType()); } 
+14
source

Create an Animal base class. Let each specific animal be inherited from the Animal. Create an abstract method in Animal called NameType that overrides each subclass. Create a List<Animal> and repeat this.

+1
source

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


All Articles