类型转换、类型安全以及is和as的使用
class Program { static void Main(string[] args) { //1、类型转换 { //隐式转换:不需要转型,因为new返回一个Employee对象,而Object是Employee的基类型 object o = new Employee(); //显示转换:需要转型,因为Employee派生自Object Employee employee = (Employee)o; } //2、类型安全 { //由于Manager是派生自Employee类型,运行正常 Manager m = new Manager(); PromoteEmployee(m); //由于DateTime不是派生自Employee类型,运行时会抛出异常 //DateTime newYears = new DateTime(2019, 8, 25); //PromoteEmployee(newYears); } //3、类型检查 is ,用is判断类型相比比较低 /* * 这是由于is操作符首先核实o是否兼容于Employee类型,再次核实o是否引用了一个Employee * * is类型检查,永远不会抛出异常,结果只会返回 true 或 false * * **/ { object o = new object(); if ((o is object)) { } if ((o is Employee)) { } } //4、类型转换 as ,用as判断类型可提升其性能 /* * as 类型转换,如果类型转换成功,则返回对象,否则返回null,此转换方式也永远不会抛出异常 * * **/ { object o = new object(); Employee e = o as Employee; if (e != null) { } } //5、类型转行 as ,测试 { object o = new object(); Employee e = o as Employee; } //6、类型转换小测试 { //编译错误,由于是显示转换,不一定成功 //B b1 = new object(); //D d1 = new object(); //运行错误,由于是显示转换,不一定成功 B b1 = new B(); D d1 = (D)b1; //运行错误,由于是显示转换,不一定成功 object o = new object(); B b2 = (B)o; } Console.ReadKey(); } //应该将Object参数类型改为Employee类型,这样在编译时就能报错 static void PromoteEmployee(object o) { Employee e = (Employee)o; } } class D : B { } class B { } public class Manager : Employee { } public class Employee { }