C# 中 override 和 new 的区别

在C#,继承类里,如果有和父类一样的方法,有两种办法可以做到,即override和new。

他们的区别在于:

new出来的方法,无法使用多态!

代码:

namespace testClass
{
    class Mammal
    {
        public Mammal()
        {
            Console.WriteLine("a new mammal birth!");

        }

        public Mammal(string name)
        {
            Console.WriteLine("a new mammal birth!"+name);

        }

        public virtual void Breathe()
        {
            Console.WriteLine("mammal breathe");
        }

        public void SuckleYoung()
        {
            Console.WriteLine("mammal suckleyoung");
        }
    }
}
namespace testClass
{
    class Horse:Mammal
    {
        public  Horse()
        {
            Console.WriteLine("a horse birth!");
        }


        public Horse(string name) : base()
        {
            Console.WriteLine("a horse birth!"+name);
        }

         public override void Breathe()
        {
            Console.WriteLine("horse breathe");
        }


        public void Trot()
        {
            Console.WriteLine("horse trot");

        }
    }
}
namespace testClass
{
    class Program
    {
        static void Main(string[] args)
        {
            Mammal mammal = new Mammal("new mammal");
            Horse horse = new Horse("new horse");

            mammal = horse;
            mammal.Breathe();
        }
    }
}

输出为horse breathe

但是如果把horse的breathe方法改成new,结果就是mammal breathe,即父类不认子类继承的breathe方法!

 本文参考 <C# step by step>

原文地址:https://www.cnblogs.com/lucalu/p/8726444.html