C#里氏转换练习(随机类型转换和对应方法调用)

tech2024-06-18  73

using System; using System.Collections.Generic; namespace oop05_里式转换 { class Program { static void Main(string[] args) { Person[] per = new Person[10]; Random rd = new Random(); for (int i = 0; i < per.Length; i++) { int rdNumber = rd.Next(1, 7); switch (rdNumber) { case 1: per[i] = new Student(); break; case 2: per[i] = new Teacher(); break; case 3: per[i] = new Handsome(); break; case 4: per[i] = new Beauty(); break; case 5: per[i] = new Beast(); break; case 6: per[i] = new Person(); break; } } for (int i = 0; i < per.Length; i++) { if (per[i] is Student) { ((Student)per[i]).StudentSayHi(); } else if (per[i] is Teacher) { ((Teacher)per[i]).TeacherSayHi(); } else if (per[i] is Handsome) { ((Handsome)per[i]).HandsomeSayHi(); } else if (per[i] is Beauty) { ((Beauty)per[i]).BeautySayHi(); } else if (per[i] is Beast) { ((Beast)per[i]).BeastSayHi(); } else { per[i].PersonSayHi(); } } Console.ReadKey(); } } public class Person { public void PersonSayHi() { Console.WriteLine("你好,我是Person类"); } } public class Student : Person { public void StudentSayHi() { Console.WriteLine("你好,我是Student类"); } } public class Teacher : Person { public void TeacherSayHi() { Console.WriteLine("你好,我是Teacher类"); } } public class Handsome : Person { public void HandsomeSayHi() { Console.WriteLine("你好,我是Handsome类"); } } public class Beauty : Person { public void BeautySayHi() { Console.WriteLine("你好,我是Beauty类"); } } public class Beast : Person { public void BeastSayHi() { Console.WriteLine("你好,我是Beast类"); } } }
最新回复(0)