C#2008与.NET 3.5 高级程序设计读书笔记(6)--继承和多态
1.基类/派生类的转换规则:
(1)隐式转换:在基类中引用派生类型总是安全的.
Employee employee = new SalesManager();
2.使用C#强制转换运算符进行显示的向下转换
//隐式转换
Employee employee = new SalesManager();
//使用C#强制转换运算符进行显式的向下转换
SalesManager salesManager = (SalesManager)employee;
(3)关键字as
使用关键字as在运行时检查某个类型是否和另外一个类型兼容
代码
SalesManager salesManager = new SalesManager();
Employee employee = salesManager as Employee;
if (employee != null)
{
Console.WriteLine("salesManager is a employee");
}
(4)关键字is
和关键字as不同,如果类型不兼容,is关键字就返回false而不是null引用.
static void FireThisPersion(Employee employee)
{
if (employee is SalesManager)
{
}
}
2.超级父类System.Object
在.NET世界中,每一个类都会从System.Object继承,即使没有显示继承改父类,编译器会自动继承Object基类