【发布时间】:2020-12-19 02:56:30
【问题描述】:
这是一个奇怪的问题,我知道您不能在 C# 中覆盖变量。也许这行不通。我正在尝试获取一个类型为类的变量,并用该类的子级覆盖它。
为了把它放在上下文中,我有一个Character 类。它有一个AttackSystem 类型的变量attackSystem。我有一个从Character 继承的NPC 类,我试图将attackSystem 重写为从AttackSystem 继承的NPCAttackSystem 类型。
这可行吗?或者,我是否把事情复杂化了太多?我是否应该不“覆盖”变量而只是在NPC 的构造函数中说attackSystem = new NPCAttackSystem()
(A) 我在做什么(不起作用):
public class Character
{
public AttackSystem attackSystem = new AttackSystem();
}
public class NPC : Character
{
public NPCAttackSystem attackSystem = new NPCAttackSystem();;
}
public class AttackSystem {}
public class NPCAttackSystem: AttackSystem {}
(B)我该怎么办?
public class Character
{
public AttackSystem attackSystem = new AttackSystem();;
}
public class NPC : Character
{
NPC()
{
attackSystem = new NPCAttackSystem();
}
}
public class AttackSystem {}
public class NPCAttackSystem: AttackSystem {}
我经常在自己的问题中回答自己的问题。只是想知道我是否可以按照我想要的方式(A)或者我是否应该以其他方式(B)。另一种方式(B)会起作用吗?我可以通过这种方式访问NPCAttackSystem 的成员吗?
抱歉所有问题,简单的 A.) 或 B.) 就可以了。
感谢您的帮助,我喜欢在这里提问。
【问题讨论】:
-
public class Character<T> where T: AttackSystem. -
你可以在一个方法里面做。现在 attachSystem 是在基类中定义的,所以你不能在继承的类中拥有另一个属性 attachsystem 除非你使用 override。
-
你的意思是像
public class Character<AttackSystem>?如果是这样,我可以添加多个像这样public class Character<AttackSystem, MotorSystem, InventorySystem>的系统吗?我的大多数基类系统都会有这样的子类。public class NPC<NPCAttackSystem, NPCMotorSystem, NPCInventory>: Character. -
public virtual AttackSystem AttackSystem { get; set; }= new AttackSystem();和public override AttackSystem AttackSystem { get; set; }= new NPCAttackSystem();我不明白问题出在哪里
标签: c# inheritance overriding multiple-inheritance