简体   繁体   English

C#-在另一个具有相同含义的类中创建类实例

[英]C# - Create class instance inside another class with same meaning

I want to create a class named Enemy , which should be used in a programmed rpg-themed-battlesystem. 我想创建一个名为Enemy的类,该类应在已编程的rpg主题战斗系统中使用。 The problem is that I would want to create multiple monster types in the Enemy class, but then I would have to create a possibility for the battlesystem with every enemy class for example Enemy.Goblin or Enemy.Golem . 问题是我想在Enemy类中创建多种怪物类型,但随后我必须为每个敌人类(例如Enemy.GoblinEnemy.Golem的战斗系统创造一种可能性。
Question: 题:
How could I achieve this by using only one parameter in the battlesystem function? 我如何在战役系统功能中仅使用一个参数来实现这一目标? I wanted to use 我想用

public static void InitiateBattle ( Player player, Enemy enemy )

but now I cannot use the Enemy.Goblin instance, because it cant implicitly convert Enemy.Goblin to Enemy . 但是现在我不能使用Enemy.Goblin实例,因为它不能将Enemy.Goblin隐式转换为Enemy How could I most easily and with minimal code fix this? 我如何最轻松地以最少的代码解决此问题?

You need to use inheritance . 您需要使用继承

public class Enemy
{
 // put all properties and methods common to all here
}

public class Goblin: Enemy
{
  // goblin specific stuff here
}

you will then be able to pass in a goblin as an enemy. 这样您就可以将小妖精作为敌人通过。

It sounds like you want to use inheritance? 听起来您想使用继承吗?

public class Enemy {}
public class Goblin : Enemy {}
public class Golem : Enemy {}

You can then pass in an instance of Goblin or Golem to your method and the statement will be valid because the compiler will 'box' your object into an instance of the parent type. 然后,您可以将GoblinGolem的实例传递给您的方法,该语句将有效,因为编译器会将您的对象“装箱”到父类型的实例中。

Then, if you want to use a member from the Goblin or Golem subclasses, you would need to 'cast' the enemy parameter variable back into the appropriate type using as : 然后,如果要使用Goblin或Golem子类中的成员,则需要使用as将“ enemy参数变量“投射”回适当的类型:

public static void InitiateBattle (Player player, Enemy enemy)
{
     var golem = enemy as Golem;
     var goblin = enemy as Goblin;
}

Make sure you check for null after the cast! 确保在转换后检查null!

Bear in mind that C# does not allow multiple-inheritance; 请记住,C#不允许多重继承。 each class can inherit from only one parent. 每个类只能从一个父级继承。

I think it would be best to use 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM