简体   繁体   中英

How to disable ToString on records

I have a record type which occurs quite often in a nested complex data structure. Because the record type has an automatically generated ToString the ToString of my bigger structure becomes way to confusing and I do not care for the string representation of my record.
So I want to have an empty string as representation for my record. Overriding ToString seems to not do anything, using StructuredFormatDisplay does not work with empty strings since it requires an input of the form "Text {Field} Text" . Right now I have

[<StructuredFormatDisplay("{}")>]
type MyRecord
    {  5 fields... }

    override __.ToString () = ""

But this results in The method MyRecord.ToString could not be found .

So what is the correct way to not have a string representation for a record type?

The comments all provide correct information about how to achieve your goal. Pulling it all together, here's what I would do in a real-world scenario where I wanted a record type to always have the empty string as its string representation:

open System

[<StructuredFormatDisplay("{StringDisplay}")>]
type MyRecord =
    {  
        A: int
        B: string
        C: decimal
        D: DateTime
        E: Guid
    }
    member __.StringDisplay = String.Empty
    override this.ToString () = this.StringDisplay

This way, regardless of what technique is used to print the record, or if its ToString method is used by an external caller, the representation will always be the same:

let record = {A = 3; B = "Test"; C = 5.6M; D = DateTime.Now; E = Guid.NewGuid()}
printfn "Structured Format Display:  %A" record
printfn "Implicit ToString Call:  %O" record
printfn "Explicit ToString Call:  %s" <| record.ToString()

This prints:

Structured Format Display:  
Implicit ToString Call:  
Explicit ToString Call:  

One thing to keep in mind is that this will even override the way the record is displayed by F# interactive. Meaning, the record evaluation itself now shows up as:

val record : MyRecord = 

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