我正在努力教自己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.)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
标准方法是x.ToString()像这样重写
override this.ToString() = sprintf "%f,%f" x y
Run Code Online (Sandbox Code Playgroud)
然后你可以打印出来
printf "%O" Some_Vect
Run Code Online (Sandbox Code Playgroud)