zoukankan      html  css  js  c++  java
  • 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>

  • 相关阅读:
    常用的VI/VIM命令
    那些年学过的一些算法
    huffman编码
    好用java库(一):java date/time api:jodatime
    linux启动
    ubuntu学习方式
    地址
    各种各样的软件
    jquery文件
    C变量与数据
  • 原文地址:https://www.cnblogs.com/lucalu/p/8726444.html
Copyright © 2011-2022 走看看