在f#中实现ac #interface:无法获得正确的类型

Jon*_*all 2 c# generics f#

我一直在试验F#,并认为,作为一个学习练习,我可以获得一个现有的c#项目,并用F#版本逐个替换类.当我尝试使用F#'class'类型实现通用c#接口时,我遇到了麻烦.

C#界面

public interface IFoo<T> where T : Thing
    {
         int DoSomething<T>(T arg);
    }
Run Code Online (Sandbox Code Playgroud)

试图实施F#.我有各种版本,这是最接近的(给我最少量的错误消息)

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

我现在得到的编译错误是:

成员'DoSomething <'T>:'T - > int'没有正确的类型来覆盖相应的抽象方法.所需的签名是'DoSomething <'T>:'T0 - > int'.

这令我感到困惑.什么是'T0?更重要的是如何正确实现此成员?

Lee*_*Lee 8

首先,通用参数来DoSomething隐藏接口T上的类型参数IFoo<T>.您可能打算使用:

public interface IFoo<T> where T : Thing
{
    int DoSomething(T arg);
}
Run Code Online (Sandbox Code Playgroud)

完成后,您可以使用以下方法实现界面:

type Foo<'T when 'T :> Thing> =
    interface IFoo<'T> with
        member this.DoSomething arg = 45
Run Code Online (Sandbox Code Playgroud)

如果你没有打算阴影的C#接口的类型参数,上面的定义仍然有效,编译器将推断的类型arg'a不是T :> Thing按要求.

  • 更直接地说,您需要提供定义它的通用参数,而不是它被引用的位置. (2认同)