【发布时间】:2019-11-24 22:10:31
【问题描述】:
让我们考虑一下这段代码:
type TransactionTypes =
| TransactionType1
| TransactionType2
type Test() =
let mutable lastTransactionType1 = DateTime.MinValue
let mutable lastTransactionType2 = DateTime.MinValue
let getLastTransaction transaction =
match transaction with
| TransactionType1 -> lastTransactionType1
| TransactionType2 -> lastTransactionType2
let updateLastTransaction transaction =
match transaction with
| TransactionType1 -> lastTransactionType1 <- DateTime.UtcNow
| TransactionType2 -> lastTransactionType2 <- DateTime.UtcNow
现在(了解到我仍在学习 F#),我想澄清几点:
类似:
let a = DateTime.Now
进行永久绑定,因此 'a' 在后续使用中总是相同的时间。
但是,我的理解是,如果有参数的话,比如:
let a anyParameter = DateTime.Now
由于参数的存在,每次都会重新评估。对吗?
在上面的代码中,两个 let 语句(getLastTransaction 和 updateLastTransaction)是类型私有的(Test)
我也可以将它们实现为:
member private this.getLastTransaction = ...
member private this.updateLastTransaction = ...
有什么理由让私有函数更喜欢 let vs. member private this? “让可变”已经暗示了这个。所以这两种形式都可以访问这些字段。
那么,一种形式相对于另一种形式的优势是什么?
【问题讨论】:
-
它将如何回答一种形式与另一种形式的优势?我问这些问题的原因是因为在 let、member 和 val 之间,到字段/方法/属性的映射有点模糊,为什么已经讨论过这个主题,我找不到我写的问题的答案
-
我可以写 let x _ = 做某事,或成员 this.x = 做某事,或成员 this.x() = 做某事......在实践中必须有一些差异。我想我总是可以将方法实现为属性,所以成员 this.x = 可能不是最好的,但这留下了我的问题:在私人情况下成员 this 与 let .. 真正的区别是什么
标签: f#