简体   繁体   中英

How to use abstract classes in c#

I am trying to make a game, in the console (it's kinda simple). I want to have multiple types of soldiers, so I thought I'd make an abstract soldier class

public abstract class Soldier
    {
        public string Name;
        public int Health;
        public float ShootingRange;
        public float MovementRange;
        public Player Owner;
        public Vector2Int Position;
        public char Symbol;
    }

The reason for this is I would like 1 list for all of the units a player has. The player class looks like this:

 public class Player
{
    public int Money = 0;
    public ConsoleColor Color;

    public List<Soldiers.Soldier> Units = new List<Soldiers.Soldier>();

    public Player(ConsoleColor c)
    {
        Color = c;
    }

    public void AddUnit(Vector2Int Position)
    {
        Units.Add(new Soldiers.Rifleman(this, Position));
    }
}

Then I wanted to implement a version of the Soldier class to make a kind of soldier I call it Rifleman:

public class Rifleman : Soldier
    {
        public int Health = 10;
        public float ShootingRange = 5f;
        public float MovementRange = 2.5f;
        public Player Owner;
        public Vector2Int Position;
        public char Symbol = Utils.MASTERKEY["Rifleman"];

        public Rifleman(Player owner, Vector2Int position)
        {
            Owner = owner;
            Position = position;
        }
    }

The problem is that in my map class (how I display and manage the game) when I go to try and pull the char representing the Rifleman class on the map, it finds it to be a null value. How could I fix this?

As @Progman and @bmm6o said, you're redefining your Symbol field. Since your List<Soldier> returns a Soldier , its Symbol field is what you're getting, which wasn't assigned.

You should either be using abstract and/or virtual properties you can override, or protected setter properties like either in the examples below showing different forms.

public abstract Soldier
{
  public abstract char Symbol { get; }
  public virtual string Name { get; } = "Soldier";
  public string Weapon { get; protected set; } = "Gun";
}

public Rifleman : Soldier
{
  public override char Symbol => 'r';
  public override string Name => nameof(Rifleman);
}

public Sniper : Soldier
{
  public Solder()
  {
    Weapon = "Rifle";
  }
  public override char Symbol => 's';
}

Fields should almost always be private, and are often unnecessary in modern versions of C# (what you see above are language features that should work with any .NET Framework or Core version).

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