带有和不带接口的F#类定义

时间:2010-10-21 15:35:29

标签: class interface f#

为什么这是可以接受的:

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。

2 个答案:

答案 0 :(得分:4)

移动接口实现上方的字段

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

答案 1 :(得分:4)

Desco的回答是正确的。至于为什么你的方法不起作用,关键是在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