【问题标题】:How to create a type parametric abstract type in F#?如何在 F# 中创建类型参数抽象类型?
【发布时间】:2020-06-01 09:25:33
【问题描述】:

我想通过以下方式创建一个抽象类型:

type IResource =
    abstract member List    : string -> List<'T>

当我实现它时,我需要一个具体类型而不是 'T(例如 int)。

type Website(stage: string) =
    member this.List    stage = (this :> IResource).List    stage
    interface IResource with
      member this.List    stage = []

是否可以在 F# 中使用它?如果我在实现中给 List 一个类型,类型检查器会抱怨我使用 int 而不是 'T。

【问题讨论】:

    标签: generics types f#


    【解决方案1】:

    通过为接口类型提供类型参数,使您的接口显式通用:

    type IResource<'T> =
        abstract member List : string -> List<'T>
    

    然后你可以在实现接口时指定类型

    type Website(stage: string) =
        member this.List stage = (this :> IResource<int>).List    stage
        interface IResource<int> with
          member this.List stage = []
    

    【讨论】:

    • 谢谢谢尔盖!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多