use*_*861 2 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"
| Int -> base.ToString()
| Str -> this
let c = Bool(false)
printfn "%A" c
Run Code Online (Sandbox Code Playgroud)
我在ToString覆盖中得到一个错误,说明"此构造函数应用于0参数但预期为1".我很确定这段代码不能编译,但它显示了我正在尝试做的事情.当我注释掉覆盖并运行代码时,c打印出"val c:MyType = Bool false".当我进入该代码时,我看到c的属性Item设置为布尔值false.我似乎无法在代码中访问此属性.即使我注释也没有c.
在这种情况下,我应该如何重写ToString?
*我很确定这些被称为复合类型.
当您使用Discriminated Union(DU)(这是该类型的适当名称)时,您需要在匹配语句中解压缩值,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
Item您看到的属性是实现细节,不能从F#代码访问.仅仅使用this不起作用,因为DU是值的包装器,所以this指的是包装器,而不是包含的值.