绅士们,
过去的程序/确定性程序员与 F# 函数式斗争......
我需要一些计数器来记录程序各个区域的计数。以下代码编译干净并且似乎可以工作,但“ctr”永远不会增加。
任何帮助表示赞赏,伊恩
type Count() as this =
let mutable ctr = 0
do
printfn "Count:Constructor: %A" ctr
member this.upctr : int =
let ctr = ctr + 1
printfn "inCount.upctr %d" ctr
ctr
let myCount = new Count()
printfn "MyCtr1 %d" (myCount.upctr)
let fred = myCount.upctr
let fred = myCount.upctr
Run Code Online (Sandbox Code Playgroud)
该值ctr
是可变的。使用:
ctr <- ctr + 1 // this will mutate the value contained in ctr
Run Code Online (Sandbox Code Playgroud)
代替
// this will create a new binding which is not mutable
// and will shadow the original ctr
let ctr = ctr + 1
Run Code Online (Sandbox Code Playgroud)
另请注意警告,它告诉您不需要 as this
在类型声明中。