我一直在尝试使用 F#,并且认为,作为一种学习练习,我可以获取一个现有的 c# 项目,并用 F# 版本一个一个地替换类。当我尝试使用 F#“类”类型实现通用 C# 接口(interface)时遇到了麻烦。
C# 接口(interface)
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
我现在得到的编译错误是:
The member 'DoSomething<'T> : 'T -> int' does not have the correct type to override the corresponding abstract method. The required signature is 'DoSomething<'T> : 'T0 -> int'.
这让我很困惑。什么是'T0?更重要的是,我该如何正确实现这个成员?
最佳答案
首先,DoSomething
的通用参数隐藏类型参数 T
在 IFoo<T>
上界面。您可能打算使用:
public interface IFoo<T> where T : Thing
{
int DoSomething(T arg);
}
完成后,您可以通过以下方式实现接口(interface):
type Foo<'T when 'T :> Thing> =
interface IFoo<'T> with
member this.DoSomething arg = 45
如果您确实打算在 C# 接口(interface)上隐藏类型参数,上述定义仍然有效,编译器将推断出 arg
的类型。成为'a
而不是 T :> Thing
根据需要。
关于c# - 在 f# : can't get the type right 中实现 C# 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23704581/