您好,登錄后才能下訂單哦!
namespace _41.里氏轉(zhuǎn)換法
{
class Program
{
//創(chuàng)建10個(gè)對(duì)象 通過(guò)一個(gè)循環(huán) 去調(diào)用他們各自打招呼的方法
//1、里氏轉(zhuǎn)換
//1)、子類可以賦值給父類
//2)、如果父類中裝的是子類對(duì)象,那么可以將這個(gè)父類強(qiáng)轉(zhuǎn)為子類對(duì)象。
static void Main(string[] args)
{
Person[] pers = new Person[10]; //新建10個(gè)對(duì)象
Random r = new Random(); //聲明一個(gè)隨機(jī)數(shù)
for (int i = 0; i <pers.Length; i++)//通過(guò)循環(huán)給Person賦值
{
int rNmuber = r.Next(1, 8);
switch (rNmuber)
{
case 1:pers[i] = new Student(); //當(dāng)1-7時(shí),子類賦值給父類
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++) // 通過(guò)一個(gè)for循環(huán)進(jìn)行取值
{
if(pers[i] is Student) //如果可以轉(zhuǎn)成student
{
((Student)pers[i]).StudentSayHello(); //父類強(qiáng)轉(zhuǎn)成子類,然后調(diào)用打招呼方法
}
else if(pers[i] is Teacher) //如果可以轉(zhuǎn)成Teacher
{
((Teacher)pers[i]).TeacherSayhello();//父類強(qiáng)轉(zhuǎn)成子類,然后調(diào)用打招呼方法
}
else if(pers[i] is Doctor)
{
((Doctor)pers[i]).DoctorSayHello(); //父類強(qiáng)轉(zhuǎn)成子類,然后調(diào)用打招呼方法
}
else if(pers[i] is Police)
{
((Police)pers[i]).PoliceSayHello(); //父類強(qiáng)轉(zhuǎn)成子類,然后調(diào)用打招呼方法
}
else if(pers[i] is Nurse)
{
((Nurse)pers[i]).NurseSayHello(); //父類強(qiáng)轉(zhuǎn)成子類,然后調(diào)用打招呼方法
}
else if(pers[i] is Driver)
{
((Driver)pers[i]).DriverSayHello(); //父類強(qiáng)轉(zhuǎn)成子類,然后調(diào)用打招呼方法
}
else
{
pers[i].PersonSayHello();
}
}
Console.ReadKey();
}
//新建類
public class Person //父類
{
public void PersonSayHello()
{
Console.WriteLine("我是父類");
}
}
public class Student:Person
{
public void StudentSayHello()
{
Console.WriteLine("我是學(xué)生");
}
}
public class Teacher : Person
{
public void TeacherSayhello()
{
Console.WriteLine("我是老師");
}
}
public class Doctor:Person
{
public void DoctorSayHello()
{
Console.WriteLine("我是醫(yī)生");
}
}
public class Police : Person
{
public void PoliceSayHello()
{
Console.WriteLine("我是警察");
}
}
public class Nurse : Person
{
public void NurseSayHello()
{
Console.WriteLine("我是護(hù)士");
}
}
public class Driver:Person
{
public void DriverSayHello()
{
Console.WriteLine("我是司機(jī)");
}
}
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。