练习
创建一个父类,四个子类,将子类赋值给父类,将父类强转为子类,随机调用子类的方法
using System;
namespace 里氏转换练习
{
class Program
{
static void Main(string[] args)
{
Person[] per = new Person[10]; //创建一个person类数组
Random r = new Random(); //创建一个随机数
for (int i = 0; i < per.Length; i++) //写一个循环,让随机产生的成员进入数组
{
int rnumber = r.Next(1, 6); //随机数1-5
switch (rnumber)//随机生成成员
{
case 1:
per[i] = new Student();
break;
case 2:
per[i] = new Meinv();
break;
case 3:
per[i] = new ShuaiGe();
break;
case 4:
per[i] = new YeShow();
break;
case 5:
per[i] = new Person();
break;
}
}
for (int i = 0; i < per.Length; i++)
{
//per[i].PersonSay();
if (per[i] is Student)//如果数组里面的成员是Student子类的,将父类强转为子类成员,并输入方法
{
((Student)per[i]).StudentSay();
}
else if (per[i] is YeShow)//依次判断
{
((YeShow)per[i]).YeShouSay();
}
else if (per[i] is Meinv)
{
((Meinv)per[i]).MeiNvSay();
}
else if (per[i] is ShuaiGe)
{
((ShuaiGe)per[i]).ShuaiGeSay();
}
else
{
per[i].PersonSay();
}
}
}
}
public class Person//创建父类Person和方法
{
public void PersonSay()
{
Console.WriteLine("我是人类");
}
}
public class Meinv : Person
{
public void MeiNvSay()
{
Console.WriteLine("我是美女");
}
}
public class ShuaiGe : Person
{
public void ShuaiGeSay()
{
Console.WriteLine("我是帅哥");
}
}
public class Student : Person
{
public void StudentSay()
{
Console.WriteLine("我是学生");
}
}
public class YeShow : Person
{
public void YeShouSay()
{
Console.WriteLine("我是野兽");
}
}
}