当我制作游戏时,我偶然发现了一个小问题.我有一个方法Attack(),必须在我的角色攻击敌人时执行.例如:
public override void Attack(Object theEnemy)
{
theEnemy.Health = theEnemy.Health - this.attack
}
Run Code Online (Sandbox Code Playgroud)
示例:我攻击一个精灵.Elf对象需要是参数,问题是参数正在寻找Object,而不是Elf.如果我想攻击其他敌人物体,如兽人,矮人等,同样如此.我需要参数能够接受任何物体.可能吗?
在这种情况下你可以使用接口,例如:
interface IEnemy
{
void TakeDamage(int attackPower);
}
public Elf: IEnemy
{
// sample implementation
public void TakeDamage(int attackPower)
{
this.Health -= attackPower - this.Defense;
}
}
// later on use IEnemy, which is implemented by all enemy creatures
void Attack(IEnemy theEnemy)
{
theEnemy.TakeDamage(attack)
}
Run Code Online (Sandbox Code Playgroud)