来源:http://blog.csdn.net/jackiezhw/article/details/2673992
在 C# 中,派生类可以包含与基类方法同名的方法。
1 using System; 2 using System.Collections.Generic; 3 4 5 public class Car 6 { 7 8 public virtual void DescribeCar() 9 { 10 Console.WriteLine("Base Car!"); 11 } 12 13 } 14 15 16 public class ConvertibleCar : Car 17 { 18 public new void DescribeCar() 19 { 20 base.DescribeCar(); 21 Console.WriteLine("Convertible Car!"); 22 } 23 } 24 25 public class DerivedConvertibleCar : ConvertibleCar 26 { 27 public new void DescribeCar() 28 { 29 base.DescribeCar(); 30 Console.WriteLine("DerivedConvertibleCar Car!"); 31 } 32 } 33 34 35 public class DerivedMinivan : Minivan 36 { 37 public override void DescribeCar() 38 { 39 base.DescribeCar(); 40 Console.WriteLine("DerivedMinivan Car!"); 41 } 42 } 43 public class Minivan : Car 44 { 45 public override void DescribeCar() 46 { 47 base.DescribeCar(); 48 Console.WriteLine("Minivan Car!"); 49 } 50 } 51 52 53 public class CarCollections 54 { 55 public static void Main() 56 { 57 List<CAR> cars = new List<CAR>(); 58 59 cars.Add(new Car()); 60 cars.Add(new ConvertibleCar()); 61 cars.Add(new Minivan()); 62 cars.Add(new DerivedConvertibleCar()); 63 cars.Add(new DerivedMinivan()); 64 foreach (Car car in cars) 65 car.DescribeCar(); 66 } 67 }
输出结果:
Base Car!【Car】 Base Car!【ConvertibleCar】 Base Car!【Minivan】 Minivan Car! Base Car!【DerivedConvertibleCar】 Base Car!【DerivedMinivan 】 Minivan Car! DerivedMinivan Car!
可以看到使用new和使用override的效果是不一样的。
C#中的Virtual、Override和new关键词理解,布布扣,bubuko.com
C#中的Virtual、Override和new关键词理解
原文:http://www.cnblogs.com/spriteflk/p/3816302.html