里氏转换
1.子类可以赋值给父类
2.如果父类中装的是子类对象,那么可将这个父类强转为子类对象。
子类对象可以调用父类中的成员,但是父类对象永远都只能调用自己的成员。
is:表示类型转换,如果能够转换成功,则返回一个true,否则返回一个false
as:表示类型转换,如果能够转换则返回对应的对象,否则返回一个null
using System;
namespace 关键字new
{
class Program
{
static void Main(string[] args)
{
//Student s = new Student();
Person p = new Student();
//is用法
// if (p is Student)
// {
// Student ss = (Student)p;
// ss.StudentSayHello();
// }
// else
// {
// Console.WriteLine("转换失败");
// }
//as用法
Student t = p as Student;
t.StudentSayHello();
}
}
public class Person
{
public void PersonSayHello()
{
Console.WriteLine("我是人类");
}
}
public class Student : Person
{
public void StudentSayHello()
{
Console.WriteLine("我是学生");
}
}
public class Teacher : Person
{
public void TeacherSayHello()
{
Console.WriteLine("我是老师");
}
}
}