在F#中初始化自动实现的属性

时间:2012-11-16 10:49:00

标签: f#

"Automatically implemented properties are part of the initialization of a type, so they must be included before any other member definitions, just like let bindings and do bindings in a type definition"

但是如果我将member val放在类型声明中的其他普通member this.属性之后,编译器就不会抱怨。好吗?

我是否正确地说,在初始化对象时初始化属性,而不是在首次调用属性时?

e.g。

   member val = let printf "%A" "initializing"
                3 with get, set

所以每次创建一个对象时都会打印“初始化?

1 个答案:

答案 0 :(得分:4)

是的,自动实现的member的初始化代码作为对象构造的一部分运行(即使您在member x.Bar = ...之前放置了一些其他member val声明):

type Test() =
  do printfn "constructor"
  member x.Bar = 
    printfn "calling Bar"
    10
  member val Foo = 
    printfn "initializing Foo" 
    3 with get, set

let t = Test()
printfn "constructed"
t.Foo

首先运行构造函数中的代码,然后执行Foo初始化(另一方面,Bar中的代码在您实际调用t.Bar之前不会被调用),所以这打印:

  

构造
  初始化Foo
  构造