1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 多态 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 /// 基类实例化对象 p 14 /// 调用基类CPerson的Print()方法 15 CPerson p = new CPerson(); 16 p.Print(); 17 18 /// 派生类实例化对象m; 19 /// 将m指向的堆托管地址赋值给基类对象p; 20 /// p 将调用派生类CMan的Print()方法; 21 CMan m = new CMan(); 22 p = m; 23 p.Print(); 24 25 /// p 将调用派生类CWoman的Print()方法; 26 CWoman w = new CWoman(); 27 p = w; 28 p.Print(); 29 30 Console.ReadLine(); 31 } 32 } 33 34 //基类 35 public class CPerson 36 { 37 public virtual void Print() 38 { 39 Console.WriteLine("基类CPerson : Print()方法 "); 40 } 41 } 42 43 // 派生类 44 public class CMan : CPerson 45 { 46 public override void Print() 47 { 48 Console.WriteLine("派生类CMan : Print()方法 "); 49 } 50 } 51 52 // 派生类 53 public class CWoman : CPerson 54 { 55 public override void Print() 56 { 57 Console.WriteLine("派生类CWoman : Print()方法 "); 58 } 59 } 60 }