gpt4 book ai didi

f# - F# 中的 ToString() 覆盖不适用于包含另一种类型的类型

转载 作者:行者123 更新时间:2023-12-04 17:39:14 25 4
gpt4 key购买 nike

我有一个类型“Team”,其中包含另一个类型“Employee”。我已经为类型“Employee”覆盖了 ToString()。但是,当我为“团队”类型执行 ToString() 时,“员工”中的详细信息使用标准 ToString() 实现进行了 pretty-print ,并且从未使用过我的重写逻辑。有人可以帮助理解为什么覆盖不起作用吗?这是代码:

type Employee =
{
name : string
address : string
}
override this.ToString() = sprintf "Hello %s" this.name

type Team =
{
employee1 : Employee
}
with member this.ToTightString =
this.ToString().Replace(" ","")


let employee = { name="Bob"; address="Unknown"; }
let team = {employee1=employee}
printfn "%s" (employee.ToString()) // Override works!
// OUTPUT: Hello Bob
printfn "--------------------"
printf "%s" team.ToTightString // Override doesn't work
// OUTPUT: {employee1={name="Bob";address="Unknown";};}

最佳答案

作为@rmunn上面已经说过,即使在包含“type1”类型的类型上调用 ToString(),也会保留 StructuredFormatDisplay 中指定的类型(例如 type1)的文本表示。这是一个例子:

open System.Text.RegularExpressions

[<StructuredFormatDisplay("name=Always Harry address={address}")>]
type Employee =
{
name : string
address : string
}

type AddressContainer =
{
employee: Employee
containerName: string
}

let address1 = { name="Bob"; address="Random City" }
let addressContainer1 = { employee=address1; containerName= "container1"}
printf "%s" (address1.ToString()) // prints "name=Always Harry address=Random City"
printf "%s" (addressContainer1.ToString()) // prints {employee = name=Always Harry address=Random City; containerName = "container1";}

关于f# - F# 中的 ToString() 覆盖不适用于包含另一种类型的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55279763/

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