簡體   English   中英

在f#中實現C#接口:無法獲得正確的類型

[英]implementing a C# interface in f#: can't get the type right

我一直在試驗F#,並認為,作為一個學習練習,我可以獲得一個現有的c#項目,並用F#版本逐個替換類。 當我嘗試使用F#'class'類型實現通用C#接口時,我遇到了麻煩。

C#界面

public interface IFoo<T> where T : Thing
    {
         int DoSomething<T>(T arg);
    }

試圖實施F#。 我有各種版本,這是最接近的(給我最少量的錯誤消息)

type Foo<'T when 'T :> Thing> =
    interface IFoo<'T> with
        member this.DoSomething<'T>(arg) : int =
            45 

我現在得到的編譯錯誤是:

成員'DoSomething <'T>:'T - > int'沒有正確的類型來覆蓋相應的抽象方法。 所需的簽名是'DoSomething <'T>:'T0 - > int'。

這令我感到困惑。 什么是'T0? 更重要的是如何正確實現此成員?

首先, DoSomething的泛型參數會影響IFoo<T>接口上的類型參數T 您可能打算使用:

public interface IFoo<T> where T : Thing
{
    int DoSomething(T arg);
}

完成后,您可以使用以下方法實現界面:

type Foo<'T when 'T :> Thing> =
    interface IFoo<'T> with
        member this.DoSomething arg = 45

如果你打算影着C#接口的類型參數,上面的定義還是工作,編譯器會推斷出的類型arg'a而不是T :> Thing的要求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM