如何设置一个接受稍后要声明的对象的参数
本文关键字:声明 参数 对象 一个 何设置 设置 | 更新日期: 2023-09-27 17:57:40
在制作游戏时,我偶然发现了一个小问题。我有一个方法Attack(),当我的角色攻击敌人时必须执行。例如:
public override void Attack(Object theEnemy)
{
theEnemy.Health = theEnemy.Health - this.attack
}
我攻击一只小精灵。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)
}
似乎任何可能被"攻击"的东西都必须实现一个可以访问所需属性和/或方法的接口。
例如,你可以做
public interface IAttackable
{
void ReduceHealth(int amount);
}
然后对任何可攻击的生物实施它,例如精灵
public class Elf : IAttackable
{
public void ReduceHealth(int amount)
{
this.Health -= amount;
}
}
然后使用
public override void Attack(IAttackable theEnemy)
{
theEnemy.ReduceHealth(this.attack);
}
您可以创建每个敌方对象实现的接口,也可以创建每个敌人对象所基于的基类。
public interface IEnemyCreature{
void ReduceHealth(int Amount)
}
public Elf: IEnemyCreature{
...
}
Edit-WalkHard已经描述了比I9-)更好的代码
最好是分离关注点并使用OOP概念。使用接口。
interface IGameMethods
{
void Attack(int yourValueForAttackMethod);
}
用于实施
public Elf: IGameMethods
{
// implementation of IGameMethods
}