3

我正在尝试自学 F#。我已经建立了一个简单的类,并希望能够打印它。

是否有一个惯用的等价于 C++ 的重载operator<<(std::ostream&,const MyClass&)可以让我打印,例如,printfn?如果不是自定义类的“标准”方式是什么?

具体来说,这里是当前的类

type Vect(x: float, y: float) = 
    new() = Vect(0.,0.)
    member this.x = x
    member this.y = y
    static member (-) (v1: Vect, v2: Vect) = 
        Vect(v1.x-v2.x,v1.y-v2.y)
    member this.Magnitude() = 
        sqrt(x**2. + y**2.)
4

2 回答 2

8

StructuredFormatDisplay也可以使用该属性。

[<StructuredFormatDisplay("Name: {FullName}")>]
type Person(first, last) =
  member val First = first
  member val Last = last
  member this.FullName = first + " " + last
  override this.ToString() = last + ", " + first

let person = Person("John", "Doe")
printfn "%O" person
> Doe, John
printfn "%A" person
> Name: John Doe
于 2013-07-09T18:38:16.293 回答
5

x.ToString()标准方法是像这样覆盖

override this.ToString() = sprintf "%f,%f" x y

然后你可以打印这个

printf "%O" Some_Vect
于 2013-07-09T11:33:19.347 回答