class - F# 成员一个内部函数,仅在第一次调用时评估
问题描述
我正在尝试对 F# 中的类使用一种聚合,就像这样member this.FullName with get() = fullName()
。您可以看到我已将其设计为调用内部函数的成员let fullName() = (string Id) +" "+ Name
,并且该值似乎在第一次调用时被评估并存储在内部。如果我修改构成函数的值,它会继续返回第一次调用的值。我怎样才能改变它?
同时,如果我更新 LiteDB 中的对象并再次读取它,如果看起来如此,或者值已更新。
和其他问题:存储在 LiteDB 中的成员和内部变量是什么。每个人?. 我怎样才能控制它?
完整的代码是:
open System
open LiteDB
open LiteDB.FSharp
[<StructuredFormatDisplay("Article #{Id}: {Name}")>]
type Article( Id: int, Name: string) as self =
let fullName = (string Id) + " " + Name
member val Id = Id //Read Only
member val Name = Name with get, set //Mutable
//[<BsonIgnore>]
member this.FullName with get() = fullName
//[<BsonIgnore>]
member this.FullName2 = (string Id) + " " + Name
[<EntryPoint>]
let main argv =
let mapper = FSharpBsonMapper()
use db = new LiteDatabase("simple.db", mapper)
let articles = db.GetCollection<Article>("articles")
let id = BsonValue(2)
// Insert
let art2 = new Article(2, "First Name")
printfn "%A" art2
printfn "fn: %s" art2.FullName
articles.Insert(art2) |> ignore
printfn "==="
// Find
let result = articles.FindById(id)
printfn "%A" result
printfn "fn: %s" result.FullName
printfn "==="
// Modify
result.Name <- "New Name"
printfn "%A" result
printfn "fn: %s" result.FullName //<- No Modified!
printfn "fn2: %s" result.FullName2 //<- No Modified!
printfn "==="
// Update Modified Changes
articles.Update(result) |> ignore
let result = articles.FindById(id)
// printfn "%%O %O" result //.ToString()
printfn "%A" result
printfn "fn: %s" result.FullName
0 // return an integer exit code
解决方案
你已经写了let fullName = (string Id) + " " + Name
。之后没有参数fullName
,因此它不是一个函数(每次调用时都评估),而是一个值(只评估一次)。如果您希望每次调用时都对其进行评估,请通过添加参数将其转换为函数:
let fullName () = (string Id) + " " + Name
推荐阅读
- c# - 计算给定行数和每行项目限制的列数
- git - 重写git历史合并两个文件
- html - 在 Powershell 的 html 表格视图中转换 Json 响应
- python - 数据框删除分类字段值高于阈值的行
- react-native - react-native 中 this.state.places 中的错误未定义
- mysql - 如果没有其他行匹配,则返回默认行的 MYSQL 查询
- mongodb - Mongodb聚合:测试字段是数字还是字母数字,如果是字母数字则将其拆分
- typescript - 扩展一组函数以接受 Typescript 中的额外参数
- python - 如何在python中修复列表索引超出范围
- java - 为什么我可以更改类中的私有属性?