static void Main(string[] args) { #region _01里氏转换 /* * 1.子类可以赋值给父类 * 2.如果父类中装的是子类对象,那么可以讲这个父类强转为子类对象 * 3.is:成功true,失败false! * as:成功返回对应的对象,失败返回null; */ //Student s = new Student(); //Person p = new Person(); //Person p = s; //子类可以赋值给父类 Person p = new Student(); //1条 Student ss = (Student)p;//2条 if (p is Teacher) { Teacher ss1 = (Teacher)p; ss1.TeacherSayHello(); } else { Console.WriteLine("转换失败"); } Teacher t = p as Teacher; ss.StudentSayHello(); string str = string.Join("|", new string[] { "1", "2", "3", "4" }); Console.WriteLine(str); #endregion Console.ReadKey(); }
static void Main(string[] args) { //创建10个对象通过一个循环去调用他们各自打招呼的方法 Person[] pers = new Person[10]; Random r = new Random(); for (int i = 0; i < pers.Length; i++) { int rNumber = r.Next(1, 7); switch (rNumber)//1-6; { case 1:pers[i]=new Student(); break; case 2: pers[i] = new Teacher(); break; case 3: pers[i] = new ShuaiGuo(); break; case 4: pers[i] = new MeiLv(); break; case 5: pers[i] = new YeShou(); break; case 6: pers[i] = new Person(); break; } } for (int i = 0; i < pers.Length; i++) { //pers[i].PersonSayHi(); if (pers[i] is Student) { ((Student)pers[i]).StudentSayHi(); } else if (pers[i] is Teacher) { ((Teacher)pers[i]).TeacherSayHi(); } else if (pers[i] is ShuaiGuo) { ((ShuaiGuo)pers[i]).ShuaiGuoSayHi(); }else if(pers[i] is YeShou){ ((YeShou)pers[i]).YeShouSayHi(); }else if(pers[i] is MeiLv){ ((MeiLv)pers[i]).MeiLvSayHi(); }else{ pers[i].PersonSayHi(); } } Console.ReadKey(); }