1 using System; 2 using System.Collections.Generic; 3 namespace inherit 4 { 5 public class Workitem 6 { 7 private static int nextid; 8 protected int ID { get; set; } 9 protected TimeSpan jobLength { get; set; } 10 protected string Title { get; set; } 11 protected string Description { get; set; } 12 public Workitem() 13 { 14 ID = 0; 15 Title = "default title"; 16 Description = "default description"; 17 jobLength = new TimeSpan(); 18 } 19 static Workitem() 20 { 21 nextid = 0; 22 } 23 public Workitem(string title, string desc, TimeSpan joblen) 24 { 25 this.ID = GetNextID(); 26 this.Title = title; 27 this.Description = desc; 28 this.jobLength = joblen; 29 } 30 protected int GetNextID() 31 { 32 return ++nextid; 33 } 34 public void Update(string title, TimeSpan joblen) 35 { 36 this.Title = title; 37 this.jobLength = joblen; 38 } 39 public override string ToString() 40 { 41 return String.Format("{0}-{1}", this.ID, this.Title); 42 } 43 } 44 public class ChangeRequest : Workitem 45 { 46 protected int originalItemID { get; set; } 47 public ChangeRequest() 48 { } 49 public ChangeRequest(string title, string desc, TimeSpan joblen, int originalid) 50 { 51 this.ID = GetNextID(); 52 this.Title = title; 53 this.Description = desc; 54 this.jobLength = joblen; 55 this.originalItemID = originalid; 56 } 57 } 58 class Program 59 { 60 static void Main() 61 { 62 Workitem item=new Workitem("Fix bugs","fix all bugs in my source code branch",new TimeSpan(4,0,0)); 63 ChangeRequest change = new ChangeRequest("change design of base class", "add members to base class", new TimeSpan(4, 0, 0), 1); 64 Console.WriteLine(item.ToString()); 65 Console.WriteLine(change.ToString()); 66 Console.ReadKey(); 67 } 68 } 69 } 70 /* Output: 71 1 - Fix Bugs 72 2 - Change design of base class 73 */
示例演示如何以 C# 表示上图所示的类关系。该示例还演示 WorkItem 如何重写虚方法 Object.ToString 以及 ChangeRequest 类如何继承该方法的 WorkItem 实现。
定义一个类从其他类派生时,派生类隐式获得基类的除构造函数和析构函数以外的所有成员。因此,派生类可以重用基类中的代码而无需重新实现这些代码。可以在派生类中添加更多成员。派生类以这种方式扩展基类的功能。
下图演示一个 WorkItem 类,该类表示某业务流程中的一个工作项。和所有的类一样,该类派生自 System.Object 并继承其所有方法。WorkItem 添加了自己的五个成员。其中包括一个构造函数,因为构造函数不能继承。ChangeRequest 继承自 WorkItem 并表示特定种类的工作项。ChangeRequest 在它从 WorkItem 和 Object 继承的成员中另外添加了两个成员。它必须添加自己的构造函数,还要添加一个成员以实现 ChangeRequest 与应用更改的原始 WorkItem 之间的关联。