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() { //此次就說明了,派生類對象可以作為基類對象進行處理 Shape[] shapes = { new Circle(), new Rectangle(), new Triangle() };
foreach (Shape s in shapes) { //調用Draw()方法的時候,調用了派生重寫的方法,而不是基類 s.Draw(); } } }