在Haxe中,您可以在接口中将类型参数约束为通用类型吗?

问题描述 投票:0回答:1

编辑:这个例子太简单了,我改掉了这个问题here

[下面有一个人为设计的示例,其中我有一个通用接口,该接口带有一个方法,该方法接受“扩展” T的V参数。然后,我有一个实现此接口的类,但后来我无法获得类型为匹配接口的方法。我该如何进行编译?是否有其他方法可以使此功能起作用而又不影响类型系统?具体错误是“字段fn与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());
    }
}

一些进一步的测试表明,我可以在类本身内将类型参数约束为泛型类型。接口的添加显示了此错误。

generics types interface haxe type-constraints
1个回答
2
投票

也许您可以这样做:

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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.