F#中的ToString()覆盖不适用于包含其他类型的类型

时间:2019-03-21 11:46:25

标签: f#

我有一个'Team'类型,其中包含另一个'Employee'类型。我已经覆盖了'Employee'类型的ToString()。但是,当我为“ Team”类型执行ToString()时,来自“ Employee”的详细信息用标准的ToString()实现漂亮地打印出来,并且从未使用我的替代逻辑。有人可以帮助您理解为何覆盖无效的原因吗?这是代码:

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";};}

1 个答案:

答案 0 :(得分:0)

正如@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";}