码迷,mamicode.com
首页 > Windows程序 > 详细

【C#】多态

时间:2018-11-17 16:12:11      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:div   err   ring   virt   实例化   stat   key   span   ati   

  public class Animal
        {
            public virtual void Eat()
            {
                Console.WriteLine("Animal eat");
                Console.ReadKey();
            }
        }

        public class Cat : Animal
        {
            public override void Eat()
            {
                Console.WriteLine("Cat eat");
                Console.ReadKey();
            }
        }

        public class Dog : Animal
        {
            public override void Eat()
            {
                Console.WriteLine("Dog eat");
                Console.ReadKey();
            }
        }
        public class Snake : Animal
        {
            public new void Eat()
            {
                Console.WriteLine("Snake eat");
                Console.ReadKey();
            }
        }

        class Tester
        {
            static void Main(string[] args)
            {
                Animal[] animals = new Animal[5];

                animals[0] = new Animal();
                animals[1] = new Cat();
                animals[2] = new Dog();
                animals[3] = new Snake();
                for (int i = 0; i < 4; i++)
                {
                    animals[i].Eat();
                }
                Snake snake = new Snake();
                snake.Eat();
            }
        }

直接上代码比较容易记

运行结果。子类重写父类,实例化父类,执行子类方法,若要执行子类new出的方法,则要实例化子类。

Animal eat
Cat eat
Dog eat
Animal eat
Snake eat

 

【C#】多态

标签:div   err   ring   virt   实例化   stat   key   span   ati   

原文地址:https://www.cnblogs.com/xuxml/p/9973862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!