父类子类转化(两种方式)

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("转换失败");
}

 

posted @ 2017-10-11 20:36  fight139  阅读(618)  评论(0编辑  收藏  举报