oiu1010110
白日梦想jun
2017-11-11 08:16

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

  • 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条回答