在示例中,我有三个类:View,FView(扩展View)和MView(扩展View)。我有MView类型的变量,并希望针对父类View检查它(即如果此变量来自类View)。是否可以获取父类(View类)? 。以下是完整示例:https://try.haxe.org/#eA594
Account Value
803 Copy values from Master data depending on Account Value
691 Copy values from Master data depending on Account Value
8010 Copy values from Master data depending on Account Value
课程观点:
class Test {
static function main() {
var v = new SView();
trace(Type.getClassName( Type.getSuperClass(Type.getClass(v))) );
}
}
类FView:
class View {
public function new() {
}
}
类SView:
class FView extends View {
public function new() {
super();
}
}
答案 0 :(得分:5)
如果你想进入基类,你可以简单地递归或迭代,直到Type.getSuperClass()
返回null
:
// at runtime: find out what is the base class of `v`
var base:Class<Dynamic> = Type.getClass(v);
while (true) {
var s = Type.getSuperClass(base);
if (s == null)
break;
base = s;
}
trace(Type.getClassName(base));
但是,您提到要执行此操作只是为了检查MView
(或SView
)是否属于View
类型。
嗯,为此,有一些更简单的替代方案......
首先,在编译类型中,您只需使用type check(或作业)来检查v:SView
unifies是否View
:
// at compile time: enforce that `v` be of type `View` or compatible with it
var v1 = (v:View); // use a type check
var v2:View = v; // or simply pass it to something expecting `View`
如果您需要在运行时执行此操作,则可以使用Std.is()
:
// at runtime: check if `v` is a subclass instance of `View`
trace(Std.is(v, View));
有关完整示例,请查看this尝试Haxe实例。