如何在F#中的复合类型中重写ToString?
我正在学习如何在F#中创建复合*类型,我遇到了一个问题。我有这个类型和一个ToString覆盖如何在F#中的复合类型中重写ToString?,f#,overriding,composite-types,F#,Overriding,Composite Types,我正在学习如何在F#中创建复合*类型,我遇到了一个问题。我有这个类型和一个ToString覆盖 type MyType = | Bool of bool | Int of int | Str of string with override this.ToString() = match this with | Bool -> if this then "I'm True" else "I'm False"
type MyType =
| Bool of bool
| Int of int
| Str of string
with override this.ToString() =
match this with
| Bool -> if this then "I'm True" else "I'm False"
| Int -> base.ToString()
| Str -> this
let c = Bool(false)
printfn "%A" c
我在ToString重写中得到一个错误,该错误表示“此构造函数应用于0个参数,但预期为1”。我很确定这段代码不会编译,但它显示了我正在尝试做的事情。当我注释掉覆盖并运行代码时,c
被打印为“val c:MyType=Bool false”。当我进入该代码时,我看到c有一个属性Item
设置为布尔值false
。但是,我似乎无法在代码中访问此属性。即使我注释了c
,也不行
在这种情况下,我应该如何超越ToString
*我很确定这些被称为复合类型。当您使用(DU)(这是该类型的合适名称)时,您需要像下面这样解压match语句中的值:
type MyType =
| Bool of bool
| Int of int
| Str of string
with override this.ToString() =
match this with
| Bool(b) -> if b then "I'm True" else "I'm False"
| Int(i) -> i.ToString()
| Str(s) -> s
let c = Bool(false)
printfn "%A" c
您看到的项
属性是一个实现细节,不打算从F#code访问。仅仅使用this
是不起作用的,因为DU是围绕值的包装,所以this
指的是包装,而不是包含的值