
class Gameobject { } class Player :Gameobject { public void Attk() { } } class Master : Gameobject { public void Attk() { } } class Boss : Gameobject { public void Attk() { } } internal class Program { static void Main(string[] args) { Gameobject master = new Master(); } }
但有个问题,我在用的时候没法用master.Attk("攻击") 因为master是属于Gameobject的
于是就有了is 和as;

static void Main(string[] args) { Gameobject master = new Master(); if (master is Master) //判断是不是这个类型的 { Master m = new Master();//转化类型 m = master as Master; master.Attk() } }
还有更简单的写法,不用中间值 m,直接(master as Master).Attk()
看起来我们不需要判定,因为我们一眼就看出来,是不是这个类的,但
Gameobject[] objs = { new Player(), new Master(), new Boss() }; for (int i = 0; i < objs.Length; i++) { if (objs[i] is Master) { (objs[i] as Master).Attk(); } else if(...) { ... } ... }
在数组里数量多了就不好看出来,节省时间就可以用判断.


题目二using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 继承 { class Master { public void Attk() { } } class Boss : Master { public void Skill() { } } class Goblin : Master { } internal class Program { static void Main(string[] args) { Master[] master = new Master[10]; for (int i = 0; i < master.Length; i++) { Random r = new Random(); int num = r.Next(0, 2); if (num == 0) { master[i] = new Boss(); } else { master[i] = new Goblin(); } } for (int i = 0; i > master.Length; i++) { if (master[i] is Boss) { (master[i] as Boss).Skill(); } else { (master[i] as Goblin).Attk(); } } } } }
本文作者:Leemoon
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!