Ada*_*ich 1 c# inheritance class
我有一个名为"Entity"的类,有两个子类:"Creature"和"Item".(我正在制作一个游戏.)生物有两个叫做"攻击"的功能,一个用于攻击生物,一个用于攻击物品.到目前为止,一切运作良好.
现在我正在研究拍摄位,所以我有一个名为SelectTarget()的函数.它需要玩家视图中的所有实体(包括生物和物品),玩家可以射击并让玩家选择一个.
所以问题在于:SelectTarget()返回一个实体,但我需要一些代码来确定该Entity是Creature还是Item,并对其进行适当处理.
因为这个问题在没有任何代码的情况下看起来很空,而且我不能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;
}
}
Run Code Online (Sandbox Code Playgroud)
(如果游戏布局的方式看起来很怪异,那就是roguelike.)
如何引入IAttackable
既实现Creature
又Item
实现的界面呢?Player.Attack
会有新的签名Player.Attack(IAttackable target)
.每个实现的对象IAttackable
都可以获得减去健康状况或检索防御值的方法(用于计算要减少的健康点),等等......