假设这些类:
public abstract class Creature
{ public abstract int MaxLevel { get; } }
public abstract class NormalCreature : Creature
{
public abstract Type Mutation { get; }
public override int MaxLevel { get { return 50; } }
}
public abstract class MutantCreature : Creature
{
public abstract Type Base { get; }
public override int MaxLevel { get { return 70; } }
}
public sealed class Human : NormalCreature
{
public override Type Mutation { get { return typeof(Superhuman); } }
...
}
public sealed class Superhuman : MutantCreature
{
public override Type Base { get { return typeof(Human); } }
...
}
public sealed class Dwarf : NormalCreature
{
public override Type Mutation { get { return typeof(DwarfOnADonkey); } }
public void SwimLikeADolphin() { ... }
...
}
public sealed class DwarfOnADonkey : MutantCreature
{
public override Type Base { get { return typeof(Dwarf); } }
// can no longer SwinLikeADolphin(), this is why DwarfOnADonkey does not heritate Dwarf
public void JumpOverTwentyFeet() { ... }
...
}
...
我如何实现这一点,从每个NormalCreature
到MutantCreature
建立连接,反之亦然,而不用重复代码? (如果Human
变异为Superhuman
,那么我可以知道Superhuman
是Human
的变异,而没有指定它。
我还考虑过另一个类,将它们与元组或数组[2]配对,但我不太喜欢这个解决方案。 我也考虑过属性,但我不知道它是否可以完成这项工作,也不知道如何正确使用它们。
答案 0 :(得分:0)
继承总是认为'是'。超人是一个人,Human
应该来自Human
但是人类是种族,而不是人类是种族。这意味着Race
无法从{{1}}派生。你可以使用术语'生物'作为人类和矮人的基类。
我不会使用类层次结构来保存对象的历史记录。
答案 1 :(得分:0)
好吧,我最终选择了这个解决方案,但我不知道它的可接受性:
public enum Race
{
Human = 0x01,
Dwarf = 0x02,
...
Mutant = 0x80,
Superhuman = Mutant | Human,
DwarfOnADonkey = Mutant | Dwarf,
...
}
public abstract Creature
{
public abstract Race Race { get; }
...
}
public abstract NormalCreature : Creature { ... }
public abstract MutantCreature : Creature { ... }
public sealed Human : NormalCreature
{
public override Race Race { get Race.Human; }
...
}
public sealed Superhuman : MutantCreature
{
public override Race Race { get Race.Superhuman; }
...
}