上代码
class Program
{
static void Main(string[] args)
{
Person p = new Student();
if (p is Teacher)
{
((Teacher)p).TeacherSayHello();
}
else
{
Console.WriteLine("转换失败");
}
// 运行结果,转换失败
Student s = p as Student;//将person转换为student对象
if (s!=null)
{
s.StudentSayHello();
}
else
{
Console.WriteLine("转换失败");
}
//运行为子类的方法
Console.ReadKey();
}
}
<mark>父类</mark>
class Person
{
public void PersonSayHello()
{
Console.WriteLine("我是父类!");
}
}
<mark>子类①</mark>
class Teacher : Person
{
public void TeacherSayHello()
{
Console.WriteLine("我是老师类!");
}
}
<mark>子类②</mark>
class Student : Person
{
public void StudentSayHello()
{
Console.WriteLine("我是学生类!");
}
}