标签:int ring 取值 转换 teacher def doc space oid
namespace _41.里氏转换法 }
}
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("我是司机");
}
}
}
}
41.C#--里氏转换法--创建10个对象 通过一个循环 去调用他们各自打招呼的方法
标签:int ring 取值 转换 teacher def doc space oid
原文地址:https://blog.51cto.com/12679593/2386359