2013-07-27 20 views
1

飛鏢代碼:如何在父類中聲明子類型?

main() { 
    var child1 = new Child1(); 
    var t = child1.childType(); 
} 

class Parent { 
    ??? childType() { 
     return this.runtimeType; 
    } 
} 

class Child1 extends Parent { 
} 

class Child2 extends Parent { 
} 

你可以看到在Parent???,我希望它引用到孩子的類型,但我不知道如何申報。

在Scala中,它可以是:

def childType(): this.type = { 
    ... 
} 

但我不知道該怎麼做,在鏢。可能嗎?如果不可能,在這裏使用的最佳類型是什麼?

回答

3

如果你真的需要的childType返回類型靜態聲明爲正確的子類型,你可以使用泛型:

class Parent<C extends Parent> { 
    C get childType => runtimeType; 
} 

class Child1 extends Parent<Child1> {} 

class Child2 extends Parent<Child2> {} 

我真的確定你需要的,雖然。你可以保留childType鍵入Parent