[英]implementing a C# interface in f#: can't get the type right
I have been experimenting with F#, and thought, as a learning exercise I could get an existing c# project and replace classes one by one with F# versions. 我一直在试验F#,并认为,作为一个学习练习,我可以获得一个现有的c#项目,并用F#版本逐个替换类。 I'm running into trouble when I try to implement a generic C# interface with a F# 'class' type. 当我尝试使用F#'class'类型实现通用C#接口时,我遇到了麻烦。
C# interface C#界面
public interface IFoo<T> where T : Thing
{
int DoSomething<T>(T arg);
}
trying to implement F#. 试图实施F#。 I've had various versions, this is the closest (giving me the least amount of error messages) 我有各种版本,这是最接近的(给我最少量的错误消息)
type Foo<'T when 'T :> Thing> =
interface IFoo<'T> with
member this.DoSomething<'T>(arg) : int =
45
the compilation error I get now is: 我现在得到的编译错误是:
The member 'DoSomething<'T> : 'T -> int' does not have the correct type to override the corresponding abstract method. 成员'DoSomething <'T>:'T - > int'没有正确的类型来覆盖相应的抽象方法。 The required signature is 'DoSomething<'T> : 'T0 -> int'. 所需的签名是'DoSomething <'T>:'T0 - > int'。
this has me baffled. 这令我感到困惑。 What is 'T0? 什么是'T0? More importantly how do I implement this member correctly? 更重要的是如何正确实现此成员?
Firstly, the generic parameter to DoSomething
shadows the type parameter T
on the IFoo<T>
interface. 首先, DoSomething
的泛型参数会影响IFoo<T>
接口上的类型参数T
You probably intend to use: 您可能打算使用:
public interface IFoo<T> where T : Thing
{
int DoSomething(T arg);
}
Once you do that, you can implement the interface with: 完成后,您可以使用以下方法实现界面:
type Foo<'T when 'T :> Thing> =
interface IFoo<'T> with
member this.DoSomething arg = 45
If you did intend to shadow the type parameter on the C# interface, the above definition will still work and the compiler will infer the type of arg
to be 'a
instead of T :> Thing
as required. 如果你是打算影着C#接口的类型参数,上面的定义还是工作,编译器会推断出的类型arg
是'a
而不是T :> Thing
的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.