C#中继承类的问题

时间:2010-04-23 22:14:44

标签: c# class inheritance

我有一个名为“Entity”的类,有两个子类:“Creature”和“Item”。 (我正在制作一个游戏。)生物有两个叫做“攻击”的功能,一个用于攻击生物,一个用于攻击物品。到目前为止,一切运作良好。

现在我正在研究拍摄位,所以我有一个名为SelectTarget()的函数。它需要玩家视图中的所有实体(包括生物和物品),玩家可以拍摄并让玩家选择一个。

所以问题在于:SelectTarget()返回一个实体,但我需要一些代码来确定该实体是生物还是物品,并对其进行适当处理。

因为这个问题在没有任何代码的情况下看起来很空,而且我不能100%确定我的解释是否足够好,这就是我所在的地方:

if (Input.Check(Key.Fire)) {
    Entity target = Game.State.SelectTarget.Run();
    this.Draw();
    if (target != null) {     
        //Player.Attack(target);
        // This won't work, because I have:
        //   Player.Attack((Creature)Target)
        //   Player.Attack((Item)Target)
        // but nothing for Entity, the parent class to Creature and Item.
        return true;
    }
}

(如果游戏布局的方式看起来很怪异,那就是roguelike。)

3 个答案:

答案 0 :(得分:9)

您正在寻找Visitor pattern

答案 1 :(得分:9)

介绍IAttackableCreature实现的界面Item怎么样? Player.Attack会有新的签名Player.Attack(IAttackable target)。实现IAttackable的每个对象都可以获得减去健康状况或检索防御值的方法(用于计算要减少的健康点),等等......

答案 2 :(得分:3)

尝试类似:

if(target is Creature)
      player.Attack(target as Creature);
else if(target is Item)
      player.Attack(target as Item);