[英]How can I set a parameter that accepts an object to be declared later on?
As I made my game, I stumbled upon a slight problem. 在制作游戏时,我偶然发现了一个小问题。 I have a method Attack() that must execute when my character attacks an enemy.
我有一个Attack()方法,当我的角色攻击敌人时必须执行该方法。 For example:
例如:
public override void Attack(Object theEnemy)
{
theEnemy.Health = theEnemy.Health - this.attack
}
Example: I attack an Elf. 例子:我攻击一个精灵。 The Elf object needs to be the parameter, the problem is that the parameter is looking for Object, not Elf.
Elf对象需要是参数,问题是参数正在寻找Object,而不是Elf。 Same goes for if I want to attack other enemy objects such as Orc, Dwarf etc. I need the parameter to be able to accept any object.
如果我想攻击其他敌方对象,例如兽人,矮人等,也是如此。我需要该参数才能接受任何对象。 Is it possible?
可能吗?
You can use interface in this case eg: 您可以在这种情况下使用界面,例如:
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)
}
Seems like anything that can be "attacked" must implement an interface giving access to the required properties and/or methods. 似乎任何可以“攻击”的事物都必须实现一个接口,以提供对所需属性和/或方法的访问。
So for example you could do 因此,例如,您可以
public interface IAttackable
{
void ReduceHealth(int amount);
}
Then implement it for any creature which is attackable - ie, Elf 然后将其应用于任何可攻击的生物-例如,精灵
public class Elf : IAttackable
{
public void ReduceHealth(int amount)
{
this.Health -= amount;
}
}
Then usage would be 然后用法是
public override void Attack(IAttackable theEnemy)
{
theEnemy.ReduceHealth(this.attack);
}
You can create an interface that each enemy object implements or you could create a base class that each enemby object is based on. 您可以创建每个敌人对象都实现的接口,也可以创建每个enemby对象所基于的基类。
public interface IEnemyCreature{
void ReduceHealth(int Amount)
}
public Elf: IEnemyCreature{
...
}
Edit - WalkHard has described the code better than I 9-) 编辑-WalkHard比我9-更好地描述了代码
Best is to Seperate the Concerns and use OOP concepts. 最好是分离顾虑并使用OOP概念。 Use Interface.
使用界面。
interface IGameMethods
{
void Attack(int yourValueForAttackMethod);
}
for implementation 实施
public Elf: IGameMethods
{
// implementation of IGameMethods
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.