C# 如何设置一个参数来接受稍后要声明的对象?
当我做游戏时,我偶然发现了一个小问题。我有一个方法Attack(),当我的角色攻击敌人时必须执行。例如:C# 如何设置一个参数来接受稍后要声明的对象?,c#,object,C#,Object,当我做游戏时,我偶然发现了一个小问题。我有一个方法Attack(),当我的角色攻击敌人时必须执行。例如: public override void Attack(Object theEnemy) { theEnemy.Health = theEnemy.Health - this.attack } 我攻击一个精灵。Elf对象需要是参数,问题是参数正在查找对象,而不是Elf。如果我想攻击其他敌人的物体,如兽人、矮人等,我需要参数来接受任何物体。可能吗?在这种情况下
public override void Attack(Object theEnemy)
{
theEnemy.Health = theEnemy.Health - this.attack
}
我攻击一个精灵。Elf对象需要是参数,问题是参数正在查找对象,而不是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)
}
在这种情况下,您可以使用接口,例如:
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)
}
最好是分离关注点并使用OOP概念。 使用接口
interface IGameMethods
{
void Attack(int yourValueForAttackMethod);
}
实施
public Elf: IGameMethods
{
// implementation of IGameMethods
}
最好是分离关注点并使用OOP概念。 使用接口
interface IGameMethods
{
void Attack(int yourValueForAttackMethod);
}
实施
public Elf: IGameMethods
{
// implementation of IGameMethods
}
似乎任何可能被“攻击”的东西都必须实现一个接口,允许访问所需的属性和/或方法 例如,你可以
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 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);
}
您可以创建每个敌方对象实现的接口,也可以创建每个enemby对象基于的基类
public interface IEnemyCreature{
void ReduceHealth(int Amount)
}
public Elf: IEnemyCreature{
...
}
编辑-WalkHard对代码的描述比I 9-更好。您可以创建每个敌方对象实现的接口,也可以创建每个enemby对象基于的基类
public interface IEnemyCreature{
void ReduceHealth(int Amount)
}
public Elf: IEnemyCreature{
...
}
编辑-WalkHard对代码的描述优于I 9-使用由所有敌方生物实现的界面?使用由所有敌方生物实现的界面?