自定义强制转换功能和摘要

时间:2018-02-09 16:44:59

标签: haxe

此代码输出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));
    }
}

1 个答案:

答案 0 :(得分:1)

实际上这样就完全无法工作,因为Std.is(value, AbstractType)总会失败,因为抽象在运行时不再存在。

请参阅https://try.haxe.org/#1Afb5,尤其是: