class Program
{ static void Main() { Person[] p = new Person[10]; Random r = new Random(); for(int i = 0; i < p.Length; i++) { int rNumber = r.Next(1,4); switch(rNumber) { case 1:p[i]=Student(); break; case 2:p[i]=Teacher(); break; case 3:p[i]=Person(); break; case 4:p[i]=DaLao(); break; } } for(int i = 0; i < p.Length; i++) { //使用is判断p[i]中装的是否是对应的子类对象, //如果是,就将父类对象强转为子类对象 //父类无法调用子类方法, 所以想要显示出子类方法,必须使用子类对象调用 if(p[i] is Student) { ((Student)p[i]).StudentSayHellow(); //如果p[i]中装的是Student对象,就将其强转为Student类型,然后调用StudentSayHellow方法 } else if(p[i] is Teacher) { ((Teacher)p[i]).Teacher.SayHellow(); } else if(p[i] is DaLao) { ((DaLao)p[i]).DaLaoSayHellow(); } else { p[i].SayHellow();//调用Person类自己的方法 } } Console.ReadKey(); }}public class Person{ public void SayHellow() { Console.WriteLine("你好,我是人类"); }}public class Student:Person{ public void StudentSayHellow() { Console.WriteLine("你好,我是学生"); }}public class Teacher:Person{ public void TeacherSayHellow() { Console.WriteLine("你好,我是老师"); }}public class DaLao:Person{ public void DaLaoSayHellow() { Console.WriteLine("你好,我是DaLao"); }}