namespace _41.里氏转换法
{
class Program
{
//创建10个对象 通过一个循环 去调用他们各自打招呼的方法
//1、里氏转换
//1)、子类可以赋值给父类
//2)、如果父类中装的是子类对象,那么可以将这个父类强转为子类对象。
static void Main(string[] args)
{
Person[] pers = new Person[10]; //新建10个对象
Random r = new Random(); //声明一个随机数
for (int i = 0; i <pers.Length; i++)//通过循环给Person赋值
{
int rNmuber = r.Next(1, 8);
switch (rNmuber)
{
case 1:pers[i] = new Student(); //当1-7时,子类赋值给父类
break;
case 2:pers[i] = new Teacher();
break;
case 3:pers[i] = new Doctor();
break;
case 4:pers[i] = new Police();
break;
case 5:pers[i] = new Nurse();
break;
case 6:pers[i] = new Driver();
break;
default:pers[i] = new Person();
break;
}
}
for (int i = 0; i < pers.Length; i++) // 通过一个for循环进行取值
{
if(pers[i] is Student) //如果可以转成student
{
((Student)pers[i]).StudentSayHello(); //父类强转成子类,然后调用打招呼方法
}
else if(pers[i] is Teacher) //如果可以转成Teacher
{
((Teacher)pers[i]).TeacherSayhello();//父类强转成子类,然后调用打招呼方法
}
else if(pers[i] is Doctor)
{
((Doctor)pers[i]).DoctorSayHello(); //父类强转成子类,然后调用打招呼方法
}
else if(pers[i] is Police)
{
((Police)pers[i]).PoliceSayHello(); //父类强转成子类,然后调用打招呼方法
}
else if(pers[i] is Nurse)
{
((Nurse)pers[i]).NurseSayHello(); //父类强转成子类,然后调用打招呼方法
}
else if(pers[i] is Driver)
{
((Driver)pers[i]).DriverSayHello(); //父类强转成子类,然后调用打招呼方法
}
else
{
pers[i].PersonSayHello();
}
}
Console.ReadKey();
}
//新建类
public class Person //父类
{
public void PersonSayHello()
{
Console.WriteLine("我是父类");
}
}
public class Student:Person
{
public void StudentSayHello()
{
Console.WriteLine("我是学生");
}
}
public class Teacher : Person
{
public void TeacherSayhello()
{
Console.WriteLine("我是老师");
}
}
public class Doctor:Person
{
public void DoctorSayHello()
{
Console.WriteLine("我是医生");
}
}
public class Police : Person
{
public void PoliceSayHello()
{
Console.WriteLine("我是警察");
}
}
public class Nurse : Person
{
public void NurseSayHello()
{
Console.WriteLine("我是护士");
}
}
public class Driver:Person
{
public void DriverSayHello()
{
Console.WriteLine("我是司机");
}
}
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。