gpt4 book ai didi

f# - 初始化成员变量的奇怪之处

转载 作者:行者123 更新时间:2023-12-04 02:47:52 25 4
gpt4 key购买 nike

我习惯于一个对象的成员变量保持它们的值,除非它们被改变。所以 F# 中的以下行为有点令人惊讶:(我有一个包含 2 个成员的类,第二个类应该通过调用 gensym 函数在构造函数中初始化)

let mutable gen_base = 0
let gensym prefix =
gen_base <- gen_base+1;
prefix + gen_base.ToString()

type C(m:int, s:string) =
member this.mm = m;
member this.x = gensym s
override this.ToString() = (this.mm.ToString()) + ", " + (this.x.ToString())

let testC =
let c = new C(1,"a")
printfn "c= %A" (c.ToString())
printfn "c again = %A" (c.ToString())

打印以下内容:

c= "1, a1"
c again = "1, a2"

为什么仅仅因为我检查了它的值就再次调用了成员 x 的初始化程序?阻止它这样做的最好方法是什么?使用访问函数?

最佳答案

来自MSDN属性页面:

Note that the expression that initializes an automatically implemented property is only evaluated upon initialization, and not every time the property is accessed. This behavior is in contrast to the behavior of an explicitly implemented property.

this.x 是显式初始化的,这意味着每次访问它时都会对其进行评估。要将其变成自动初始化的属性,您必须将其更改为:

member val x = gensym s

关于f# - 初始化成员变量的奇怪之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18498520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com