首页 > 解决方案 > F#: [] vs 覆盖 __.ToString()。¿ 怎么了?

问题描述

dotnet 2.2.203 上下文:在 Ubuntu 18.04 台式机上的容器化环境中运行 F#

问题:StructuredFormatDisplay组合记录中的 不起作用。是不是错了?这些是代码

[<StructuredFormatDisplay("{SizeGb}GB")>]
type Disk = 
    { SizeGb : int }
    override __.ToString() = sprintf "<%dGB>" __.SizeGb

[<StructuredFormatDisplay("Computer #{Id}: {Manufacturer}/{DiskCount}:{Disks}")>]
type Computer =
    { Id: int
      mutable Manufacturer: string
      mutable Disks: Disk list }
      override __.ToString() = sprintf "#%d<%s>%O" __.Id __.Manufacturer __.Disks


[<EntryPoint>]
let main argv =

    let myPc =
        { Id = 0
          Manufacturer = "Computers Inc."
          Disks =
            [ { SizeGb = 100 }
              { SizeGb = 250 }
              { SizeGb = 500 } ] }

    printfn "%%O = %O" myPc 
    printfn "%%A = %A" myPc   
    0

和输出

%O = #0<Computers Inc.>[<100GB>; <250GB>; <500GB>]
%A = Computer #0: Computers Inc./3:[...GB; ...GB; ...GB]

计算机记录中磁盘记录的 %A 模式只打印一些……点!

但是 %O 印刷得很好。

标签: f#attributesrecordtostring

解决方案


我确认这个问题也发生在我的上下文中。

当您直接在磁盘列表上打印 %A 时,输出没问题:

printfn "%A" [{SizeGb = 10}] // output: [10GB]

但是,当磁盘列表像您的代码那样间接打印时:

[<StructuredFormatDisplay("Computer #{Id}: {Manufacturer}/{DiskCount}:{Disks}")>]

我们收到点。

我认为这是 F# 核心库的错误。一种解决方法可能是添加一个新的字符串属性来保存磁盘列表的格式化字符串,并改用该属性:

[<StructuredFormatDisplay("Computer #{Id}: {Manufacturer}/{DiskCount}:{DisksStr}")>]
type Computer =
{ Id: int
  mutable Manufacturer: string
  mutable Disks: Disk list }
  member this.DisksStr = sprintf "%A" this.Disks

推荐阅读