【问题标题】:F# class definition with and without interface带和不带接口的 F# 类定义
【发布时间】:2010-10-21 15:35:29
【问题描述】:

为什么这是可以接受的:

type SomeClass<'T> =
    val mutable id : int
    val mutable result : 'T

但这不是:

type SomeIface = 
    abstract id : int

type SomeClass<'T> = 
    interface SomeIface with
        val mutable id : int
        val mutable result : 'T

编译器抱怨我使用 'val' 告诉我使用 'member' 但我不能使用 mutable。

【问题讨论】:

    标签: class interface f#


    【解决方案1】:

    德斯科的回答是正确的。至于为什么你的方法不起作用,关键是在F#中,当你有类似的东西时

    interface Iface with
       [indented lines here]
    

    缩进的行只能包含接口成员的实现。它们不应包含您正在定义的类型的其他字段或成员(例如您的案例中的两个可变字段)。因此 desco 的答案有效,如下所示:

    type SomeIface = 
        abstract id : int
    
    type SomeClass<'T> = 
        interface SomeIface with
            member this.id = this.id
        val mutable id : int
        val mutable result : 'T
    

    【讨论】:

      【解决方案2】:

      将字段移到接口实现之上

      type SomeIface = 
          abstract id : int
      
      type SomeClass<'T>() = 
          [<DefaultValue>]
          val mutable id : int
          [<DefaultValue>]
          val mutable result : 'T
          interface SomeIface with
              member this.id = this.id
      
      let x = SomeClass<int>(id = 10)
      let y : SomeIface = upcast x
      printfn "%d" y.id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-28
        • 2023-01-05
        • 1970-01-01
        相关资源
        最近更新 更多