using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace learn_collection
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ArrayList arrayList = new ArrayList();
            arrayList.Add(new Chicken("SuSan"));
            arrayList.Add(new Cow("John"));
            foreach (Animal item in arrayList)
            {
                Console.WriteLine($"抓到一只动物,动物是{item.ToString()}");
                Console.WriteLine($"抓到一只动物,动物是{item.GetType()}");

                if (item.ToString().Contains("Cow")){
                    (item as Cow).MakeMilk();
                }
                else
                {
                    (item as Chicken).MakeEgg();
                }
            }
            // 把农场的鸡都卖出去
            for (int i = (arrayList.Count -1 ); i>=0; i--)
            {
                arrayList.RemoveAt(i);
            }
            Console.WriteLine($"农场现在有{arrayList.Count}只动物");
            // 农场再购买一批动物,
            // 由于Cow和Chicken具有共同的基类,所以可以使用Animal作为类型声明来声明一个动物数组
            Animal[] animals = new Animal[] {new Cow("Hello"), new Chicken("World")};
            // 集合可以通过AddRange来把一个子数组\列表一起加进来
            arrayList.AddRange(animals);
            
            Console.WriteLine($"农场现在有{arrayList.Count}只动物");
            // 卖出所有动物
            arrayList.Clear();
            Console.WriteLine($"农场现在有{arrayList.Count}只动物");

            Console.ReadKey();

        }
    }

    public abstract class Animal
    {
        protected string name;
        public string Name { get; set; }
        public Animal() => name = "The animal no name";
        public Animal(string newName) => name = newName;
        public void Feed() => Console.WriteLine($"{name} has been feed");
        public void Show() => Console.WriteLine($"{name} has been feed");
    }
    public class Cow : Animal
    {
        public Cow(string newName) : base(newName){
            Console.WriteLine($"你生产了一头牛:{name}");
        }
        public void MakeMilk()
        {
            Console.WriteLine($"奶牛{name}产了一升奶");
        }
        ~Cow()
        {
            Console.WriteLine($"你把牛{name}卖了");
        }
    }
    public class Chicken : Animal
    {
        public Chicken(string newName) : base(newName)
        {
            Console.WriteLine($"你生产了一只鸡{name}");
        }
        public void MakeEgg()
        {
            Console.WriteLine($"鸡{name}下了一个蛋");
        }
        ~Chicken()
        {
            Console.WriteLine($"你把鸡{name}卖了");
        }
    }
}

执行结果

你生产了一只鸡SuSan
你生产了一头牛:John
抓到一只动物,动物是learn_collection.Chicken
抓到一只动物,动物是learn_collection.Chicken
鸡SuSan下了一个蛋
抓到一只动物,动物是learn_collection.Cow
抓到一只动物,动物是learn_collection.Cow
奶牛John产了一升奶
农场现在有0只动物
你生产了一头牛:Hello
你生产了一只鸡World
农场现在有2只动物
农场现在有0只动物
posted on 2023-01-20 23:56  盈盈的月儿  阅读(10)  评论(0编辑  收藏  举报