F#:封闭与私有值

时间:2011-05-04 10:10:08

标签: f# closures

假设不会对以下类型进行进一步修改或添加,那么这种方式与另一种方式相比是否有任何优势(除了第二个示例的较少打字和更好的可读性和效率)?

    type MyType<'T> (_initVal : 'T) =
        let getSetFns () =
            let value = ref _initVal
            (fun () -> value.Value), (fun _value -> value := _value)
        let getVal, setVal = getSetFns ()
        member this.Value with get () = getVal () and set _value = setVal _value

......或......

    type MyType<'T> (_initVal : 'T) =
        let value = ref _initVal
        member this.Value with get () = value.Value and set _value = value := _value

1 个答案:

答案 0 :(得分:5)

第二个更短,所以我会去那。您可能需要考虑使用let mutable而不是参考单元格,它会稍微提高性能(尽管您不太可能注意到很多差异)。

为了提供更多的上下文,使用闭包来隐藏值,就像在第一种情况下那样,这是一种很好的技术,但是这里的值已经被隐藏了,所以为什么还要再次隐藏它呢?