当前位置:编程学习 > C#/ASP.NET >>

关于隐藏和用重写的区别

//隐藏 
public class a
    {
        public float speed;
        public float Run(float distance)
        {
            return distance / speed;
        }
    }

    public class b : a
    {
        public  b()
        {
            speed = 40;
        }
        public new  float Run(float distance)
        {
            return 1.6f * base.Run(distance);
        }
    }


    class Program
    {

        static void Main()
        {
            b t1 = new b();
            Console.WriteLine("卡车行驶1000公里需{0}小时",t1.Run(1000));
            a a1 = t1;
            Console.WriteLine("汽车行驶1000公里需 {0}小时", a1.Run(1000));
            Console.Read();
        }



    }
输出结果为:卡车行驶1000公里需40小时
汽车行驶1000公里需25小时

//重写:
 public class a
    {
        public float speed;
        public  virtual  float   Run(float distance)
        {
            return distance / speed;
        }
    }

    public class b : a
    {
        public  b()
        {
            speed = 40;
        }
        public override  float Run(float distance)
        {
            return 1.6f * base.Run(distance);
        }
    }


    class Program
    {

        static void Main()
        {
            b t1 = new b();
            Console.WriteLine("卡车行驶1000公里需{0}小时",t1.Run(1000));
            a a1 = t1;
            Console.WriteLine("汽车行驶1000公里需 {0}小时", a1.Run(1000));
            Console.Read();
        }



    }
输出结果为:卡车行驶1000公里需40小时
汽车行驶1000公里需40小时

怎么结果不一样?还有那个a a1=t1;怎么解释这个语句;  想半天也没能明白;
--------------------编程问答-------------------- a1 = t1,就是a1指向了t1,他俩是同一个东西 --------------------编程问答-------------------- 意思就是实际上是个b,但下面要调用的是a.Run()

因为b有override这个Run()方法,所以最后执行的是b.Run()





--------------------编程问答--------------------
引用 楼主 u013091899 的回复:
怎么结果不一样?还有那个a a1=t1;怎么解释这个语句;  想半天也没能明白;


a a1=t1就是面向对象里面的多态。
其实别人说的再多最后还得靠你自己去理解,即使在这里我跟你说了,你也不明白。
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,