经常需要扩展现有类型来添加功能(行为和数据)

  • 例如,假定已经有Person类,可创建Employee类并在其中添加EmployeeIdDepartment等员工特有的属性

也可以采取相反的操作

  • 例如,假定已有在PDA中使用的Contact类,现在想为PDA添加行事历支持.可为次创建Appointment
// Derive from one class to another
public class PdaItem
{
	public string Name {get; set;}
	public DateTime LastUpdated {get; set;}
}
// Define the Contact class as inheriting the PdaItem class

public class Contact : PdaItem
{
	public string Address {get; set;}
	public string Phone {get; set;}
}
  • 展示如何访问 Contact 中定义的属性
public class Program
{
	static void Main()
	{
		Contact contact = new Contact();
		contact.Name = "Charons";
	}
}
  • 虽然 Contact没有直接定义Name属性,但Contact的所有实例都可访问来自PdaItemName属性,并把它作为Contact的一部分使用
  • 此外,从Contact派生的其它任何类也会继承PdaItem类的成员
  • 该继承链没有限制,每个派生类都拥有由其所有基类公开的所有成员
public class PdaItem : object
{
	// ...
}
public class Appointment : PdaItem
{
	// ...
}
public class Contact : PdaItem
{
	// ...
}
public class Customer : Contact
{
	// ...
}
posted on 2022-10-18 13:50  charons  阅读(34)  评论(0编辑  收藏  举报