首页 > 解决方案 > 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

标签: classf#litedb

解决方案


你已经写了let fullName = (string Id) + " " + Name。之后没有参数fullName,因此它不是一个函数(每次调用时都评估),而是一个值(只评估一次)。如果您希望每次调用时都对其进行评估,请通过添加参数将其转换为函数:

let fullName () = (string Id) + " " + Name

推荐阅读