internalclassProgram { staticvoidMain(string[] args) { //里氏替换原则 用父类容器 装载 子类对象 GameObject player = new Player(); GameObject monster = new Monster(); GameObject boss = new Boss();
GameObject[] objects = new GameObject[] { new Player(), new Monster(), new Boss() }; } }
internalclassProgram { staticvoidMain(string[] args) { GameObject player = new Player(); GameObject[] objects = new GameObject[] { new Player(), new Monster(), new Boss() };
if (player is Player) { Console.WriteLine("是Player类型的"); (player as Player).PlayerAtk(); }
//一般is和as配合使用,is来确保对象是指定类对象,防止as返回null导致报错 for (int i = 0; i < objects.Length; i++) { if (objects[i] is Player) { (objects[i] as Player).PlayerAtk(); } elseif (objects[i] is Monster) { (objects[i] as Monster).MonsterAtk(); } elseif (objects[i] is Boss) { (objects[i] as Boss).BossAtk(); } } } }