里氏转换
1,子类可以赋值给父类
换句话说,如果一个地方需要一个父类,那么我们可以给一个子类代替
我要的是一个人,你给我一个御姐还是一个萝莉我不在乎(笑)
1 class Person 2 { 3 public void SayHellow() 4 { 5 Console.WriteLine("Person"); 6 } 7 } 8 class Student : Person 9 { 10 public void SayHellow() 11 { 12 Console.WriteLine("Student"); 13 } 14 } 15 class Teacher:Person 16 { 17 public void SayHellow() 18 { 19 Console.WriteLine("Teacher"); 20 } 21 } 22 23 24 class Program 25 { 26 27 static void Main(string[] args) 28 { 29 Student st = new Student(); 30 Person pe = st; 31 Console.WriteLine(pe.GetType().ToString()); 32 pe.SayHellow(); 33 Student st2 = (Student)pe; 34 st2.SayHellow(); 35 36 Console.ReadKey(); 37 } 38 } 39 /*输出为: 40 ConsoleApplication2.Student 41 Person 42 Student 43 */
29.30行可以简写为:
1 Person pe = new Student();
2,如果父类中装的是子类对象,那么可以将这个父类强制转换为子类对象
这个人是一个萝莉,那么我就可以把她当作萝莉对待,但我不能把她当作御姐
前面代码中的
1 Student st2 = (Student)pe;
就是这个意思,这里因为pe虽然是person类型的,但里面装的是student
如执行
1 Teacher st2 = (Teacher)pe;
就会抛异常
也就是说,这个人说一个学生,你可以要他去做学生的事情,但是不能让他去做老师的事情。
is And as
is,如果能够转换,返回true,否则返回false
1 if(pe is Teacher) 2 { 3 Console.WriteLine("老师"); 4 }else if(pe is Student) 5 { 6 Console.WriteLine("学生"); 7 }
结果输出:学生
as,如果能够转换,返回转换后的对象,否则返回null
1 Student st2 = pe as Student; 2 st2.SayHellow(); 3 Teacher te = pe as Teacher; 4 if(te==null) 5 { 6 Console.WriteLine("null"); 7 } 8 //输出结果为:学生,null
转载于:https://www.cnblogs.com/Yukisora/p/7017509.html