简体   繁体   English

抽象类的孙子继承

[英]Abstract class grandchildren inheritance

I'm trying to create a (rather clumsy) little game and I've come to a problem. 我正在尝试创建一个(不太笨拙的)小游戏,但遇到了问题。 I have a class tree as follows: 我有一个如下的类树:

  • Entity 实体
    • Character 字符
      • Player 播放机
      • Enemy 敌人
    • Static 静态的
      • Stairs 楼梯
      • OtherEncounter OtherEncounter

Now I intend to implement a generator which should generate a map based on some simple heuristics and via Entity constructor add encounters to some Tiles. 现在,我打算实现一个生成器,该生成器应基于一些简单的试探法生成一个映射,并通过Entity构造函数将遭遇添加到某些Tiles中。 For that I chose to use " Entity e " parameter in my Tile contructor. 为此,我选择在Tile构造器中使用“ Entity e ”参数。

Now for getting the correct type I set up a virtual method in all classes to return their exact type. 现在,为了获取正确的类型,我在所有类中都设置了一个虚拟方法以返回其确切类型。 That being abstract both in Entity.cs and Character.cs . Entity.csCharacter.cs中都是抽象的。 But as expected, it doesn't do much good to inherit an abstract method and make it abstract again. 但是,正如预期的那样,继承一个抽象方法并再次使其抽象化并没有多大用处。

Thus, my question is, is there any kind of "correct" implementation or is there just some simple workaround? 因此,我的问题是,是否存在任何类型的“正确”实现,还是仅存在一些简单的解决方法? I could always just skip the method in Entity.cs and create two distinct in both Character.cs and Static.cs , but that just seems too... redneck-y. 我总是可以跳过Entity.cs中的方法,并在Character.csStatic.cs中创建两个不同的方法,但这似乎也太...乡下人了。

TL;DR: How to inherit abstract method in grandchildren while not declaring in children. TL; DR:如何在未声明子级的情况下继承子级的抽象方法。

Assuming Character is abstract, you don't have to implement it in Character at all. 假设Character是抽象的,则根本不需要在Character中实现它。 See this example: 请参阅以下示例:

public abstract class Parent
{
    public abstract string Name {get;}
}

public abstract class Child : Parent
{

}

public class Grandchild: Child
{
    public override string Name { get { return "Test"; } }
}

Because Child is also abstract, you don't need to redeclare any methods as abstract , so it just passes the implementation requirement onto Grandchild . 由于Child也是抽象的,因此您无需将任何方法重新声明为abstract ,因此只需将实现要求传递给Grandchild

Try it online 在线尝试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM