在 Haxe 中,是否可以在接口中使用泛型类型约束类型参数?



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

下面我有一个人为的例子,其中我有一个通用接口,其中包含一个接受"扩展"T的V参数的方法。然后我有一个实现此接口的类,但是我无法获取与接口匹配的方法的类型类型。我如何编译它?有没有另一种方法可以在不影响类型系统的情况下使其功能化?具体错误是"字段 fn 的类型与约束间中的类型不同"。这是在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 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());
}
}

最新更新