1、里氏转换
1)、子类可以赋值给父类
2)、如果父类中装的是子类对象,那么可以将这个父类强转为子类对象。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace _03里氏转换练习 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 //创建10个对象 通过一个循环 去调用他们各自打招呼的方法 14 //Student s = new Student(); 15 //Person p = new Person(); 16 //ShuaiGuo sg = new ShuaiGuo(); 17 18 Person[] pers = new Person[10]; 19 Random r = new Random(); 20 for (int i = 0; i < pers.Length; i++) 21 { 22 int rNumber = r.Next(1, 7); 23 switch (rNumber)//1-6 24 { 25 case 1: pers[i] = new Student(); 26 break; 27 case 2: pers[i] = new Teacher(); 28 break; 29 case 3: pers[i] = new ShuaiGuo(); 30 break; 31 case 4: pers[i] = new MeiLv(); 32 break; 33 case 5: pers[i] = new YeShou(); 34 break; 35 case 6: pers[i] = new Person(); 36 break; 37 } 38 } 39 40 41 for (int i = 0; i < pers.Length; i++) 42 { 43 // pers[i].PersonSayHi(); 44 if (pers[i] is Student) 45 { 46 ((Student)pers[i]).StudentSayHi(); 47 // pers[i].PersonSayHi(); 48 } 49 else if (pers[i] is Teacher) 50 { 51 ((Teacher)pers[i]).TeacherSayHi(); 52 } 53 else if (pers[i] is ShuaiGuo) 54 { 55 ((ShuaiGuo)pers[i]).ShuaiGuoSayHi(); 56 } 57 else if (pers[i] is YeShou) 58 { 59 ((YeShou)pers[i]).YeShouSayHi(); 60 } 61 else if (pers[i] is MeiLv) 62 { 63 ((MeiLv)pers[i]).MeiLvSayHi(); 64 } 65 else 66 { 67 pers[i].PersonSayHi(); 68 } 69 70 } 71 Console.ReadKey(); 72 73 } 74 } 75 76 public class Person 77 { 78 public void PersonSayHi() 79 { 80 Console.WriteLine("我是人类"); 81 } 82 } 83 84 85 public class Student : Person 86 { 87 public void StudentSayHi() 88 { 89 Console.WriteLine("我是学生"); 90 } 91 } 92 93 public class Teacher : Person 94 { 95 public void TeacherSayHi() 96 { 97 Console.WriteLine("我是老师"); 98 } 99 } 100 101 102 public class MeiLv : Person 103 { 104 public void MeiLvSayHi() 105 { 106 Console.WriteLine("我是镁铝"); 107 } 108 } 109 110 111 public class ShuaiGuo : Person 112 { 113 public void ShuaiGuoSayHi() 114 { 115 Console.WriteLine("我是帅锅"); 116 } 117 } 118 119 120 public class YeShou : Person 121 { 122 public void YeShouSayHi() 123 { 124 Console.WriteLine("我是野兽"); 125 } 126 } 127 128 129 }