class Shape { public virtual void Draw() { Console.WriteLine("Draw a shape"); } } class Circle : Shape { public override void Draw() { Console.WriteLine("Draw a circle"); } } class Rectangle : Shape { public override void Draw() { Console.WriteLine("Draw a Rectangle"); } } class Triangle : Shape { public override void Draw() { Console.WriteLine("Draw a Triangle"); } } class Programm { static void Main() { //此次就說明了,派生類對(duì)象可以作為基類對(duì)象進(jìn)行處理 Shape[] shapes = { new Circle(), new Rectangle(), new Triangle() };
foreach (Shape s in shapes) { //調(diào)用Draw()方法的時(shí)候,調(diào)用了派生重寫的方法,而不是基類 s.Draw(); } } }