此代码输出 Null<_Test.Bar_Impl_>
.我想让它输出 Foo
但我明白为什么它不能那样工作。但也许我能以某种方式克服这个限制。
我的主要目标是创建类似于 cast
的函数,但返回 null 而不是抛出异常。它应该与摘要一起使用。
class Foo {
}
abstract Bar(Foo) {
}
class MyCast {
inline static public function doCast<T>(value: Any, type: Class<T>): Null<T> {
return Std.is(value, type) ? cast value : null;
}
}
class Test {
static function main() {
$type(MyCast.doCast(null, Bar));
}
}
最佳答案
实际上这样根本行不通,因为 Std.is(value, AbstractType)
总是会失败,因为抽象在运行时不再存在。
参见 https://try.haxe.org/#1Afb5 ,尤其是:
- 使用
@:forward
从Bar
实例访问foo
( forward doc ) - 使用
from Foo
将Foo
实例安全地转换为Bar
实例(请参阅 implicit cast doc)(请注意,此功能本身可能是正是您想要实现的目标:https://try.haxe.org/#cc903 )
关于haxe - 自定义转换函数和摘要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48710430/