简体   繁体   中英

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. 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 .
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 . 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.

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 :

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!

Bear in mind that C# does not allow multiple-inheritance; 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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