C#-里氏替换原则
概念:任何父类出现的地方,子类都可以替代
语法表现:父类容器装子类对象 ,因为子类对象包含了父类的所有内容
作用:方便进行对象的存储和管理
is & as
-
is:判断一个对象是否是指定类对象。返回bool → 是为真,不是为假
-
as:将一个对象转换为指定类对象。返回值指定类型对象 → 成功返回指定类型对象,失败返回null
注意:不能用子类容器装父类对象
class GameObject{}class Player:GameObject{public void PlayerAtk(){Console.WriteLine("玩家攻击");}}class Monster:GameObject{public void MonsterAtk(){Console.WriteLine("怪物攻击");}}class Boss:GameObject{public void BossAtk(){Console.WriteLine("Boss攻击");}}class Program{static void Main(string[] args){Console.WriteLine("里氏替换原则");//里氏替换原则 用父类容器 装载子类对象GameObject player = new Player();GameObject monster = new Monster();GameObject boss = new Boss();if( player is Player ){//Player p = player as Player;//转换失败,p中存储的就是null//p.PlayerAtk();(player as Player).PlayerAtk();}GameObject[] objects = new GameObject[] { new Player(), new Monster(), new Boss() };for (int i = 0; i < objects.Length; i++){if( objects[i] is Player ){(objects[i] as Player).PlayerAtk();}else if( objects[i] is Monster ){(objects[i] as Monster).MonsterAtk();}else if (objects[i] is Boss){(objects[i] as Boss).BossAtk();}}}}
}