f# - 如何在F#中以复合类型覆盖ToString?

标签 f# overriding composite-types

我正在学习有关在F#中创建Composite *类型的问题,但遇到了问题。我有这种类型和一个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具有设置为boolean Item的属性false。我似乎无法在代码中访问此属性。即使我注释了c也没有。

在这种情况下,我应该如何覆盖ToString?

*我很确定这些称为复合类型。

最佳答案

当使用Discriminated Union(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

您看到的Item属性是实现的详细信息,不能从F#代码中访问。仅使用this无效,因为DU是值的包装器,因此this引用包装器,而不是包含的值。

关于f# - 如何在F#中以复合类型覆盖ToString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27361674/

相关文章:

Java 覆盖错误

c# - C# Npgsql 传递的复合类型数组作为存储过程输入

multidimensional-array - Julia:制作自定义类型的空/初始化多维数组

dictionary - Julia 中的复合类型 : Dictionaries as a named field?

c# - 我可以对 C# 方法使用 F# 的 Ticked Function name notation 吗?

scala - Scala 是否有等价于 F#'s "类型的“?

asynchronous - F#:相当于 OCaml 异步

f# - 如何从 Fable 中的 NPM 模块导入函数?

Android:覆盖 shouldOverrideUrlLoading 在 HTC 设备上不起作用

java - 添加参数后覆盖具有泛型返回类型的方法失败