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

标签 f#

我有一个类型“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/

相关文章:

f# - 在 F# 中按字符串拆分字符串

f# - 如何使 ionide-fsharp 格式器在 VSCode 中工作

methods - F# - 调用方法并分配给构造函数中的属性

asynchronous - 运行超时的异步计算

f# - 为什么在大量情况下使用 struct 修饰 DU 时,F# 运行时会抛出无效程序错误?

f# - 为什么 Moq 验证方法调用会引发异常?

c# - F# 中是否有 C# 和 VB 兼容的 System.Void*? (关闭指向非托管 Alloc 的指针?)

F# 交互,API 对 dll 引用的限制

F# 前向管道从 int 转换为 bigint

interface - F# 将对象强制转换为接口(interface)