繁体   English   中英

在 Haxe 中,您可以在接口中使用泛型类型来约束类型参数吗?

[英]In Haxe, can you constrain a type parameter with a generic type in an interface?

编辑:这个例子被归结为太多了,我在这里改写了这个问题

下面我有一个人为的示例,其中我有一个通用接口,该接口带有一个接受“扩展”T 的 V 参数的方法。然后我有一个实现此接口的 class,但是我无法获取该方法的类型类型以匹配界面。 我如何让它编译? 是否有另一种方法可以在不影响类型系统的情况下使其正常工作? 具体错误是“Field fn has different type than in ConstraintInter”。 这是在 Haxe 4.0.5 上。

class TestParent { public function new() {} }
class TestChild extends TestParent { public function new() { super(); } }

interface ConstraintInter<T>
{
    public function fn<V:T>(arg:V):Void;
}

class ConstraintTest implements ConstraintInter<TestParent>
{
    public function new () {}

    public function fn<V:TestParent>(arg:V):Void
    {
        trace(arg);
    }

    public function caller()
    {
        fn(new TestParent());
        fn(new TestChild());
    }
}

一些进一步的测试表明,我可以仅在 class 本身内使用泛型类型来约束类型参数。 界面的添加使这个错误浮出水面。

也许你可以这样做:

class TestParent { public function new() {} }
class TestChild extends TestParent { public function new() { super(); } }

interface ConstraintInter<T>
{
    function fn(arg:T):Void;
}

class ConstraintTest implements ConstraintInter<TestParent>
{
    public function new () {}

    public function fn(arg:TestParent):Void
    {
        trace(arg);
    }

    public function caller()
    {
        fn(new TestParent());
        fn(new TestChild());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM