gpt4 book ai didi

generics - 如何检查该对象是 Haxe 中泛型的实例

转载 作者:行者123 更新时间:2023-12-03 06:29:11 24 4
gpt4 key购买 nike

我正在寻找一种安全的方法来根据对象类型 fork 逻辑。我还没有找到如何检查一个对象是否属于特定的泛型类型。

class Test {
static function main() {
var aa = new AA<Int>();
//ERROR: Cast type parameters must be Dynamic
//var a:A<Int> = cast(aa, A<Int>);

//ERROR: Unexpected )
//var a:A<Int> = Std.instance(aa, A<Int>);

//OK, but throw run-time exception with flash target.
var a:A<Int> = cast aa;
a.printName();

//Run-time exception
a = cast "String is obviously wrong type";
}
}

class A<T> {
public function new () { }
public function printName() {
trace("Generic name: A");
}
}

class AA<T> extends A<T> {
public function new () { super(); }
override public function printName() {
trace("Generic name AA");
}
}

是否有合法的方法来检查对象是否属于泛型类型?

最佳答案

通常没有很好的方法来做到这一点,因为该信息在运行时不再可用。您可以使用相同的解决方法 often suggested for Java ,它将泛型类型存储在您的类中:

class Main {
static function main() {
var a = new A<Int>(Int);

trace(a.typeParamIs(Int)); // true
trace(a.typeParamIs(Bool)); // false
}
}

class A<T> {
var type:Any;

public function new (type:Any) {
this.type = type;
}

public function typeParamIs(type:Any):Bool {
return this.type == type;
}
}

或者,您可以使用 Type.typeOf()如果 A 有一个 T 类型的字段,就像这样:

class Main {
static function main() {
checkType(new A<Int>(5)); // Int
checkType(new A<Bool>(true)); // Bool
checkType(new A<B>(new B())); // B
checkType(new A<B>(null)); // unhandled type TNull
}

static function checkType<T>(a:A<T>) {
trace(switch (Type.typeof(a.value)) {
case TInt: "Int";
case TBool: "Bool";
case TClass(cls) if (cls == B): "B";
case other: throw "unhandled type " + other;
});
}
}

class A<T> {
public var value:T;
public function new (value:T) {
this.value = value;
}
}

class B {
public function new() {}
}

如您所见,虽然这通常有效,但在某些情况下可能会导致意外行为 - 例如当 valuenull 时。另请记住 Type.typeOf() 的文档:

May vary per platform. Assumptions regarding this should be minimized to avoid surprises.

<小时/>

进一步阅读:mailing list thread不久前已经讨论过这个问题。那里提到了一个宏解决方案,以防您不需要在运行时知道类型。

关于generics - 如何检查该对象是 Haxe 中泛型的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42171036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com