1.概念:
是面向对象七大原则中最重要的原则.
任何父类出现的地方,子类都可以替代.
父类容器可以装子类对象.子类容器不能装父类.
2.用法
class GameObject
{
}
class Player : GameObject
{
public void PlayerFunc()
{
}
}
class Boos : GameObject
{
}
class Program
{
static void Main(string[] args)
{
//里氏替换,父类容器可以装子类
GameObject player = new Player();
//此时player不能调用Player类的成员,它已经是GameObject类了
}
}
3.is 和 as
is判断一个对象是否为指定对象,返回值bool.
static void Main(string[] args)
{
//里氏替换,父类容器可以装子类
GameObject player = new Player();
//此时player不能调用Player类的成员,它已经是GameObject类了
if(player is Player)
{
//判断player是不是Player类
}
}
as将一个对象转换为指定类对象.
若成功,返回指定类型对象;失败返回空.
static void Main(string[] args)
{
//里氏替换,父类容器可以装子类
GameObject player = new Player();
//此时player不能调用Player类的成员,即使它本质还是Player类
if(player is Player)
{
//判断player是不是Player类
//此处会进入函数,player还是Player
}
Player p = player as Player;
//以下会返回空
//Boos b = player as Boos;//两者没有关联
}
is,as通常搭配使用
//已知player本质还是Player,但却不能用Player的成员
Player p2 = player as Player;//类型转换
p2.PlayerFunc();//可以了
参考子类<唐老狮C#教程>