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>

  • 相关阅读:
    第二章Redis管理实战
    第一章Redis入门部署及持久化介绍
    数据库命令
    第一章MySQL介绍及安装
    第十一章 MHA高可用及读写分离
    第八章 日志管理
    第九章 备份和恢复
    第十章 主从复制
    关系型数据库和非关系型数据库的对比
    MySQL面试题
  • 原文地址:https://www.cnblogs.com/lucalu/p/8726444.html
Copyright © 2011-2022 走看看