Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在F#中的复合类型中重写ToString?_F#_Overriding_Composite Types - Fatal编程技术网

如何在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"

我正在学习如何在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
我在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
指的是包装,而不是包含的值