我正在努力教自己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.)
答案 0 :(得分: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
答案 1 :(得分:5)
标准方法是覆盖x.ToString()
,如此
override this.ToString() = sprintf "%f,%f" x y
然后您可以使用
进行打印printf "%O" Some_Vect