假设不会对以下类型进行进一步的修改或添加,那么这种方式与另一种方式相比是否有任何优势(除了第二个示例的较少打字和更好的可读性和效率)?
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
Run Code Online (Sandbox Code Playgroud)
... 要么...
type MyType<'T> (_initVal : 'T) =
let value = ref _initVal
member this.Value with get () = value.Value and set _value = value := _value
Run Code Online (Sandbox Code Playgroud)
第二个是更短的,所以我会去那.您可能想要考虑使用let mutable而不是参考单元格,它会稍微提高性能(尽管您不太可能注意到很多差异).
为了给出更多的上下文,使用闭包来隐藏值,就像在第一种情况下那样,这是一种很好的技术,但是这里的值已经被隐藏了,那么为什么还要再次隐藏呢?