C#多态机制

 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 : DrawingObject
14 {
15     public override void Draw()
16     {
17         Console.WriteLine("I'm a Line.");
18     }
19 }
20 
21 public class Circle : DrawingObject
22 {
23     public override void Draw()
24     {
25         Console.WriteLine("I'm a Circle.");
26     }
27 }
28 
29 public class Square : DrawingObject
30 {
31     public override void Draw()
32     {
33         Console.WriteLine("I'm a Square.");
34     }
35 }
36 
37 using System;
38 
39 public class DrawDemo
40 {
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指代父类。

原文地址:https://www.cnblogs.com/johnpher/p/2741287.html