简体   繁体   中英

ToString() override in F# doesn't work for a type containing another type

I have a type 'Team' which contains another type 'Employee'. I have overridden the ToString() for the type 'Employee'. However, when I do ToString() for the type 'Team', the details from 'Employee' is pretty-printed with the standard ToString() implementation and my overriding logic was never used. Can someone help understand why the override didn't work? Here is the code:

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

As @rmunn has said above, the textual representation of a type (say, type1) specified in StructuredFormatDisplay is retained even if one calls ToString() on a type that contains the 'type1' type. Here's an example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM