class Person { public void PersonSay() { Console.WriteLine("person"); } } class Student : Person { public void StudentSay() { Console.WriteLine("Student"); } } class Teacher : Person { public void TeacherSay() { Console.WriteLine("Teacher"); } }
1,使用is关键字
Person per = new Student(); if(per is Teacher) { ((Teacher)per).TeacherSay(); } else { Console.WriteLine("转化失败"); }
2.使用as关键字
//如果转换失败,则te为null Teacher te = per as Teacher; if (te != null) { te.TeacherSay(); } else { Console.WriteLine("转换失败"); }