要求:
用C#写一个程序,实现下图功能
实现:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _03_里氏转换练习 { class Program { static void Main(string[] args) { //创建一个对象 通过一个循环 去调用他们各自打招呼的方法 //对于一个父类对象,既可以赋值父类实例,也可以赋值子类实例 //体现里氏转换第一条 子类可以赋值给父类 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) { case 1: pers[i]=new Student(); //体现里氏转换第二条 如果父类中装的是子类对象,那么可以将父类强制转换为子类 ((Student)pers[i]).StudentSayHi(); break; case 2: pers[i]=new Teacher(); ((Teacher)pers[i]).TeacherSayHi(); break; case 3: pers[i]=new ShuaiGuo(); ((ShuaiGuo)pers[i]).ShuaiGuoSayHi(); break; case 4: pers[i]=new MeiNv(); ((MeiNv)pers[i]).MeinvSayHi(); break; case 5: pers[i]=new YeShou(); ((YeShou)pers[i]).YeShouSayHi(); break; case 6: pers[i]=new Person(); pers[i].PersonSayHi(); break; } } Console.ReadKey(); } } public class Person { public void PersonSayHi() { Console.WriteLine("我是人类"); } } public class Student : Person { public void StudentSayHi() { Console.WriteLine("我是学生"); } } public class Teacher : Person { public void TeacherSayHi() { Console.WriteLine("我是老师"); } } public class MeiNv : Person { public void MeinvSayHi() { Console.WriteLine("我是美女"); } } public class ShuaiGuo : Person { public void ShuaiGuoSayHi() { Console.WriteLine("我是帅锅"); } } public class YeShou : Person { public void YeShouSayHi() { Console.WriteLine("我是野兽"); } } }