假设我有两节课:

class PlayerManagerParent {
   public function new(){
   }
}

class GameManagerParent {
   public var playerManager:PlayerManagerParent();

   public function new(){
   }
}

然后我将其子类化为
class PlayerManagerChild extends PlayerManagerParent {
   public function new(){
      super();
   }

   public function someMethod(){
   }
}

class GameManagerChild extends GameManagerParent {

   public function new(){
      super();
      this.playerManager = new PlayerManagerChild();
   }
}

然后,我创建GameManagerChild的实例,并想要访问someMethod():
var gameManager:GameManagerChild = new GameManagerChild();
gameManager.playerManager.someMethod();

我当然不能做,因为gameManager.playerManager是 undefined playerManager:PlayerManagerParentsomeMethod()类型,编译器/类型检查器给我错误。

如何在不声明父类中的someMethod()或将playerManager类型设置为Dynamic的情况下解决此问题(这是一种选择,但后来我无法遍历playerManager中的可迭代字段)?

最佳答案

您可以为此使用受约束的参数化类型:

class PlayerManagerParent {
   public function new(){
   }
}

class GameManagerParent<T:PlayerManagerParent> {
   public var playerManager:T;

   public function new(){
   }
}

这样,您可以像这样扩展:
class PlayerManagerChild extends PlayerManagerParent {
   public function new(){
      super();
   }

   public function someMethod(){
   }
}

class GameManagerChild extends GameManagerParent<PlayerManagerChild> {

   public function new(){
      super();
      this.playerManager = new PlayerManagerChild();
   }
}

这允许您执行以下操作:
var child = new GameManagerChild();
child.playerManager.someMethod();

实时示例:
http://try.haxe.org/#21bfC

关于inheritance - Haxe-如何将变量声明为父类或子类的实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33349718/

10-09 17:17