简体   繁体   中英

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

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. For that I chose to use " Entity e " parameter in my Tile contructor.

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 . 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.

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

Assuming Character is abstract, you don't have to implement it in Character at all. 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 .

Try it online

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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