1 using System; 2 3 public class DrawingObject 4 { 5 public virtual void Draw() 6 { 7 Console.WriteLine("I'm just a generic drawing object."); 8 } 9 }10 11 using System;12 13 public class Line : DrawingObject14 {15 public override void Draw()16 {17 Console.WriteLine("I'm a Line.");18 }19 }20 21 public class Circle : DrawingObject22 {23 public override void Draw()24 {25 Console.WriteLine("I'm a Circle.");26 }27 }28 29 public class Square : DrawingObject30 {31 public override void Draw()32 {33 Console.WriteLine("I'm a Square.");34 }35 }36 37 using System;38 39 public class DrawDemo40 {41 public static int Main( )42 {43 DrawingObject[] dObj = new DrawingObject[4];44 45 dObj[0] = new Line();46 dObj[1] = new Circle();47 dObj[2] = new Square();48 dObj[3] = new DrawingObject();49 50 foreach (DrawingObject drawObj in dObj)51 {52 drawObj.Draw();53 }54 55 return 0;56 }57 }58 59 Output:60 61 I'm a Line.62 I'm a Circle.63 I'm a Square.64 I'm just a generic drawing object.
與C++相比,C#是一門明確的語言。子類重載了父類的函數要用new,重載了虛函數要用override,還能直接用base指代父類。