繁体   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