作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在寻找一种安全的方法来根据对象类型 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() {}
}
如您所见,虽然这通常有效,但在某些情况下可能会导致意外行为 - 例如当 value
为 null
时。另请记住 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/
我是一名优秀的程序员,十分优秀!