简体   繁体   English

如何在记录上禁用ToString

[英]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. 因为记录类型有一个自动生成ToStringToString我更大的结构变成方式混乱,我不关心我的纪录的字符串表示。
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" . 重写ToString似乎没有做任何事情,使用StructuredFormatDisplay不能使用空字符串,因为它需要输入"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 . 但是这导致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: 这样,无论使用什么技术来打印记录,或者如果外部调用者使用其ToString方法,表示将始终是相同的:

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. 要记住的一件事是,这甚至会覆盖F#interactive显示记录的方式。 Meaning, the record evaluation itself now shows up as: 意思是,记录评估本身现在显示为:

val record : MyRecord = 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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