[英]C# Inheritence HW Assignment; Single Class for multiple parents?
This is for a HW assignment, so it shouldn't be very difficult.这是一个硬件任务,所以应该不是很困难。 In any case, we are supposed to create a base class of a Weapon and then child classes of MeleeWeapon ,Spell, Projectile, each with additional weapon attributes.
在任何情况下,我们都应该创建一个 Weapon 的基类,然后是 MeleeWeapon 、Spell、Projectile 的子类,每个类都有额外的武器属性。 That part is not so difficult.
那部分不是那么难。 I am getting stuck with the following:
我遇到了以下问题:
"Create a class that represents a Player with a Name and a Weapon" “创建一个代表具有名称和武器的玩家的类”
I can manage creating a player class, but I'm not sure how to account for the weapon.我可以管理创建一个玩家类,但我不知道如何解释武器。
Do I have three different player classes such as public class Player : Spell: Weapon or public class Player: MeleeWeapon : Weapon?我是否有三个不同的玩家类,例如公共类 Player : Spell: Weapon 或公共类 Player: MeleeWeapon : Weapon? I feel like there should be a way to have one player class, but I'm getting flustered with how to do that.
我觉得应该有一种方法可以让一个玩家类,但我对如何做到这一点感到心慌。 The player class also needs a constructor;
播放器类还需要一个构造函数; again this isn't too hard, but I don't know how to account for the choices in weapon type unless I have more than one player class.
同样,这并不太难,但我不知道如何考虑武器类型的选择,除非我有不止一个玩家职业。
Basically, it seems like I want to have one grand child class (Player) -> three possible child classes (MeleeWeapon, Spell, Projectile) -> one parent class (Weapon), but I'm confusing myself here.基本上,我似乎想要一个大子类(玩家)-> 三个可能的子类(近战武器、法术、投射物)-> 一个父类(武器),但我在这里很困惑。
You're entirely mis-reading the requirement.你完全误解了要求。 Take a closer look:
细看:
Create a class that represents a Player with a Name and a Weapon
创建一个代表具有名称和武器的玩家的类
It's not saying that a Player is a Name and a Weapon, it's saying that a Player has a Name and a Weapon.不是说玩家是名字和武器,而是说玩家有名字和武器。
The Player
class should have two properties: Name
and Weapon
. Player
类应该有两个属性: Name
和Weapon
。 This has nothing to do with inheritance.这与继承无关。
You are confused.你很困惑。 Take a step back and follow the instructions:
退后一步并按照说明进行操作:
Create a class that represents a Player...
创建一个代表玩家的类...
public class Player {}
...with a Name...
...有一个名字...
public class Player
{
public string Name { get; set; }
}
...and a Weapon.
……还有武器。
public class Player
{
public string Name { get; set; }
public Weapon EquippedWeapon { get; set; }
}
You can now create different players with different weapons:您现在可以使用不同的武器创建不同的玩家:
var alice = new Player { Name = "Alice", EquippedWeapon = new MeleeWeapon() };
var bob = new Player { Name = "Bob", EquippedWeapon = new Spell() };
The assignment asks you to use a has-a relationship between player and weapon instead of is-a作业要求您在玩家和武器之间使用has-a关系,而不是is-a
So in your Player class you will have因此,在您的 Player 类中,您将拥有
class Player
{
public string Name {get; protected set;}
public Weapon CurrentWeapon {get; protected set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.