重写
派生类与基类中方法名、返回参数类型、参数个数均一致,就称派生类重写了基类中的方法。
using System; using System.Collections.Generic; namespace Day0 { class Program { static void Main(string[] args) { Transport transport = new Transport(); Car car = new Car(); Bicycle bicycle = new Bicycle(); transport.Drive(); transport.Refuel(); Console.WriteLine("transport oil = "+transport.oil); Console.WriteLine("=============="); transport = car; transport.Drive(); transport.Refuel(); Console.WriteLine("transport oil = " + transport.oil); car.Drive(); car.Refuel(); Console.WriteLine("transport oil = " + transport.oil); Console.WriteLine("car oil = " + car.oil); Console.WriteLine("=============="); transport = bicycle; transport.Drive(); transport.Refuel(); Console.WriteLine("transport oil = " + transport.oil); bicycle.Drive(); bicycle.Refuel(); Console.WriteLine("transport oil = " + transport.oil); Console.WriteLine("bicyle oil = " + bicycle.oil); } } class Transport { public int oil = 100; public virtual void Drive() { Console.WriteLine("驾驶交通工具..."); oil -= 20; } public void Refuel() { Console.WriteLine("默认加注燃料"); oil += 20; } } class Car : Transport { public override void Drive() { oil -= 30; Console.WriteLine("驾驶小轿车..."); } public new void Refuel() { oil += 30; Console.WriteLine("小汽车加注燃料"); } } class Bicycle : Transport { public override void Drive() { oil -= 0; Console.WriteLine("骑自行车..."); } public new void Refuel() { oil += 0; Console.WriteLine("自行车加注燃料"); } } }
运行结果
可以看出重写是多态的,当我们调用Drive方法时候,子类方法是覆盖掉父类中的方法的;而对于隐藏父类方法并不会被覆盖。
归其原因,重写是子类方法表添加新的记录,运行时修改父级方法表中地址,所以transport 是因为Drive方法地址被修改了出现多态。(动态绑定)
而隐藏仅仅是在子类方法表中添加新的记录,子类型引用调用子类型方法(Refuel),父类型引用调用父类Refuel方法(静态绑定)编译时便确定。
标签:oil,Console,浅谈,C#,Drive,WriteLine,重写,Refuel,transport From: https://www.cnblogs.com/happyu/p/18153176