白日梦想jun 2017-11-11 08:16 采纳率: 100%
浏览 1268
已采纳

C#中基类的引用指向派生类时,不理解隐藏方法的输出结果

对于隐藏方法不明白的是:
(1)当基类的引用指向派生类时,即 Car bike  = new Bike("bike");bike的run为什么是用的基类 Car的方法呢?
(2)当用派生类引用指向派生类时,即 Bike bike1  = new Bike("bike1");bike1的run这个时候才是用的派生类Bike的run方法.
但是对于方法重写的话,Car bike  = new Bike("bike");Bike bike1  = new Bike("bike1");这两种方式都是调用的派生类中的方法。所以不太明白上述隐藏方法书输出的结果。谢谢指点。
     class Car {
        public string name;
        public void run() {
            Console.WriteLine(name+" is runing !!!!");
        }
        virtual public void stopRun() {
            Console.WriteLine(name + "stop run !!!!");
        }
    }
    class Automobile:Car {
        public Automobile(string name) 
        {
            this.name = name;
        }
        new public void run() {
            Console.WriteLine(name + " is runing");
        }
        override public void stopRun()
        {
            Console.WriteLine(name + " stop run");
        }
    }
    class Bike : Car
    {
        public Bike(string name) {
            this.name = name;
        }
       new public void run()
        {
            Console.WriteLine(name + " is runing");
        }
       override public void stopRun()
       {
           Console.WriteLine(name + " stop run");
       }
    }
    class testHide
    {
        static void Main(string[] args)
        {
            Automobile automobile = new Automobile("automobile");
            automobile.run(); //"automobile is runing"  
            automobile.stopRun();  //"automobile stop run"



            Car bike  = new Bike("bike");
            car.run();  //"bike is runing !!!!"  //对于这里的输出不太理解
            car.stopRun();//"bike stop run"

            Bike bike1 = new Bike("bike1");
            bike1.run();  //"bike1 is runing"
            bike1.stopRun();//"bike1 stop run"


        }
    }
  • 写回答

1条回答 默认 最新

  • threenewbee 2017-11-11 15:56
    关注

    Car bike = new Bike("bike");
    run如果是virtual,看new Bike,如果是new,看Car

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱