一个很简单的泛型类型List的示例,帮助理解泛型的概念。

时间:2023-02-05 20:49:55
    public abstract class Animal
    {
        protected string name;
        public Animal(string newName)
        {
            name = newName;
        }
        public void Feed()
        {
            Console.WriteLine("{0} has been fed.", name);
        }
    }
    public class Cow : Animal
    {
        public Cow(string newName) : base(newName)
        {
           
        }
    }
    public class Chicken : Animal
    {
        public Chicken(string newName) : base(newName)
        {
 
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Animal> animalCollection = new List<Animal>();
            animalCollection.Add(new Cow("Jack"));
            animalCollection.Add(new Chicken("Vera"));
            foreach (Animal myAnimal in animalCollection)
            {
                myAnimal.Feed();
            }
            Console.ReadKey();
        }
 }
运行结果为:Jack has been fed.
                      Vera has been fed.