C# - 在另一个具有相同含义的 class 中创建 class 实例
C# - Create class instance inside another class with same meaning
我想创建一个名为 Enemy
的 class,它应该在编程的 rpg 主题战斗系统中使用。问题是我想在 Enemy
class 中创建多个怪物类型,但是我必须为每个敌人 class 的战斗系统创建一个可能性,例如 Enemy.Goblin
或 Enemy.Golem
.
问题:
我如何通过在 battlesystem 函数中仅使用一个参数来实现这一点?我想用
public static void InitiateBattle ( Player player, Enemy enemy )
但现在我无法使用 Enemy.Goblin
实例,因为它无法将 Enemy.Goblin
隐式转换为 Enemy
。我怎样才能最轻松地用最少的代码解决这个问题?
您需要使用 inheritance。
public class Enemy
{
// put all properties and methods common to all here
}
public class Goblin: Enemy
{
// goblin specific stuff here
}
然后你就可以把地精当成敌人了。
听起来你想使用继承?
public class Enemy {}
public class Goblin : Enemy {}
public class Golem : Enemy {}
然后您可以将 Goblin
或 Golem
的实例传递给您的方法,该语句将有效,因为编译器会将 'box' 您的 object 转换为parent 类型的实例。
然后,如果你想使用来自 Goblin 或 Golem subclasses 的成员,你需要将 'cast' enemy
参数变量变回适当的类型,使用as
:
public static void InitiateBattle (Player player, Enemy enemy)
{
var golem = enemy as Golem;
var goblin = enemy as Goblin;
}
确保在转换后检查是否为 null!
请记住,C# 不允许 multiple-inheritance;每个 class 只能继承一个 parent.
我觉得还是用interface比较好
public interface IEnemy
{
//e.g.
public void Attack();
}
public class Goblin : IEnemy
{
public void Attack()
{
throw new System.NotImplementedException();
}
}
public class Battle
{
public static void InitiateBattle(Player player, IEnemy enemy);
}
我想创建一个名为 Enemy
的 class,它应该在编程的 rpg 主题战斗系统中使用。问题是我想在 Enemy
class 中创建多个怪物类型,但是我必须为每个敌人 class 的战斗系统创建一个可能性,例如 Enemy.Goblin
或 Enemy.Golem
.
问题:
我如何通过在 battlesystem 函数中仅使用一个参数来实现这一点?我想用
public static void InitiateBattle ( Player player, Enemy enemy )
但现在我无法使用 Enemy.Goblin
实例,因为它无法将 Enemy.Goblin
隐式转换为 Enemy
。我怎样才能最轻松地用最少的代码解决这个问题?
您需要使用 inheritance。
public class Enemy
{
// put all properties and methods common to all here
}
public class Goblin: Enemy
{
// goblin specific stuff here
}
然后你就可以把地精当成敌人了。
听起来你想使用继承?
public class Enemy {}
public class Goblin : Enemy {}
public class Golem : Enemy {}
然后您可以将 Goblin
或 Golem
的实例传递给您的方法,该语句将有效,因为编译器会将 'box' 您的 object 转换为parent 类型的实例。
然后,如果你想使用来自 Goblin 或 Golem subclasses 的成员,你需要将 'cast' enemy
参数变量变回适当的类型,使用as
:
public static void InitiateBattle (Player player, Enemy enemy)
{
var golem = enemy as Golem;
var goblin = enemy as Goblin;
}
确保在转换后检查是否为 null!
请记住,C# 不允许 multiple-inheritance;每个 class 只能继承一个 parent.
我觉得还是用interface比较好
public interface IEnemy
{
//e.g.
public void Attack();
}
public class Goblin : IEnemy
{
public void Attack()
{
throw new System.NotImplementedException();
}
}
public class Battle
{
public static void InitiateBattle(Player player, IEnemy enemy);
}