例题:创建10个对象,通过一个循环,去调用他们各自打招呼方法
代码实现如下:
class Meilv:Person
{
public void MeiLvSayHello()
{
Console.WriteLine("我是美铝");
}
}
public class Person
{
public void PersonSayHello()
{
Console.WriteLine("我是父类");
}
}
class ShuaiGuo:Person
{
public void ShuaiGuoSayHello()
{
Console.WriteLine("我是帅锅");
}
}
class Student:Person
{
public void StudentSayHello()
{
Console.WriteLine("我是学生");
}
}
public class Teacher:Person
{
public void TeacherSayHello()
{
Console.WriteLine("我是老师");
}
}
class YeShou:Person
{
public void YeShouSayHello()
{
Console.WriteLine("我是野兽");
}
}
class Program
{
static void Main(string[] args)
{
Person[] per = new Person[10];
Random r = new Random();
for (int i = 0; i < per.Length; i++)
{
int rNumber = r.Next(1, 7);
switch (rNumber)//1-6
{
case 1:
per[i] = new Student();
break;
case 2:
per[i] = new Teacher();
break;
case 3:
per[i] = new ShuaiGuo();
break;
case 4:
per[i] = new Meilv();
break;
case 5:
per[i] = new YeShou();
break;
case 6:
per[i] = new Person();
break;
}
}
for (int i = 0; i < per.Length; i++)
{
if (per[i] is Student)
{
((Student)per[i]).StudentSayHello();
}
else if (per[i] is Teacher)
{
((Teacher)per[i]).TeacherSayHello();
}
else if (per[i] is ShuaiGuo)
{
((ShuaiGuo )per[i]).ShuaiGuoSayHello();
}
else if (per[i] is Meilv)
{
((Meilv)per[i]).MeiLvSayHello();
}
else if (per[i] is YeShou)
{
((YeShou)per[i]).YeShouSayHello();
}
else
{
per[i].PersonSayHello();
}
}
}
}
运行结果如下: