如何在对象表达式中实现接口自动属性

时间:2018-07-12 16:26:34

标签: f#

在以下示例中,代替???的内容:

type IFace =
    abstract MyProp : bool with get, set

let createImplementation () =
    { new IFace with
        member this.MyProp = ??? }

1 个答案:

答案 0 :(得分:5)

语法有点奇怪。您必须分别定义getter和setter并用and分开:

let createImplementation () =
    { new IFace with
        member this.MyProp 
            with get() = true
            and set x = () 
    }

但是,当然,这样的属性是没有用的,因为二传手什么也没做。它没有地方可放置值。

如何处理此问题取决于您的实现方式。我能想到的最简单的方法之一就是为该属性声明一个可变存储:

let createImplementation () =
    let mutable myProp_Value = true
    { new IFace with
        member this.MyProp 
            with get() = myProp_Value
            and set x = myProp_Value <- x
    }