簡體   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