[英]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. 问题是在我的地图类(如何显示和管理游戏)中,当我尝试在地图上提取表示Rifleman类的char时,它发现它是一个空值。 How could I fix this? 我该如何解决?
As @Progman and @bmm6o said, you're redefining your Symbol
field. 正如@Progman和@ bmm6o所说,您正在重新定义Symbol
字段。 Since your List<Soldier>
returns a Soldier
, its Symbol
field is what you're getting, which wasn't assigned. 由于您的List<Soldier>
返回一个Soldier
,因此它的Symbol
字段就是您要获取的(未分配)。
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. 您应该使用可以覆盖的抽象和/或虚拟属性,或者使用受保护的setter属性,如下面显示不同形式的示例中所示。
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). 字段几乎应该始终是私有的,并且在现代C#版本中通常是不必要的(上面看到的是应与任何.NET Framework或Core版本一起使用的语言功能)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.