2012-11-16 86 views
2

"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"初始化在F#

自動實現的屬性但是,如果我以後在類型聲明中的其他普通member this.性質把member val的編譯器不抱怨。沒關係?

我正確地說,初始化一個對象時,而不是當屬性第一次被調用時,該屬性被初始化?

例如

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

所以每次我創建一個對象,它會打印出「初始化時間?

+2

你嘗試運行呢? –

回答

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代碼,在th Ë另一方面,不叫,直到你實際調用t.Bar),所以這個打印:

構造
初始化符
構建