c# - 在 f# : can't get the type right 中实现 C# 接口(interface)

标签 c# generics f#

我一直在尝试使用 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 的通用参数隐藏类型参数 TIFoo<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/

相关文章:

javascript - Moment JS 日期到 C# 日期

c# - 在静态类上查找泛型方法

java - 将对象数组转换为持有类型 T 的集合的指定子类的方法(生成 JList)

f# - 如果F#支持void类型,为什么我需要使用单位类型?

使用 Json.Net : Error converting value to type 的 C# 枚举反序列化

c# - 为什么我的下拉列表没有填满文本框?

C# 将焦点属性应用于 FlowLayoutPanel,如按钮行为

c# - 接受过滤条件和要过滤的属性的通用 Linq to Entities 过滤方法

f# - FSharp.Data Http Utilities - 是否可以不需要响应?

parsing - 在 .NET Core 上用 F# 解析 YAML 的最佳方法是什么?