我有一个记录类型,它经常出现在嵌套的复杂数据结构中.因为记录类型有一个自动生成ToString的ToString我更大的结构变得混乱的方式,我不关心我的记录的字符串表示.
所以我希望有一个空字符串作为我的记录的表示.覆盖ToString似乎没有做任何事情,使用StructuredFormatDisplay不能使用空字符串,因为它需要输入表单"Text {Field} Text".现在我有
[<StructuredFormatDisplay("{}")>]
type MyRecord
{ 5 fields... }
override __.ToString () = ""
Run Code Online (Sandbox Code Playgroud)
但这导致了The method MyRecord.ToString could not be found.
那么没有记录类型的字符串表示的正确方法是什么?
评论都提供了有关如何实现目标的正确信息.将它们全部拉到一起,这就是我在现实场景中要做的事情,我希望记录类型总是将空字符串作为其字符串表示:
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
Run Code Online (Sandbox Code Playgroud)
这样,无论使用什么技术来打印记录,或者如果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()
Run Code Online (Sandbox Code Playgroud)
这打印:
Structured Format Display:
Implicit ToString Call:
Explicit ToString Call:
Run Code Online (Sandbox Code Playgroud)
要记住的一件事是,这甚至会覆盖F#interactive显示记录的方式.意思是,记录评估本身现在显示为:
val record : MyRecord =
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |