f# - 如何正确覆盖受约束的方法

标签 f# type-constraints

如何覆盖方法 Zero在下面的代码中,我可以返回 Euro(0)用于 type Euro 中的定义

[<AbstractClass>] 
type Currency () =
    abstract member Zero<'T when 'T :> Currency > : unit -> 'T

type Euro (value: int) =
    inherit Currency()
    member this.Value = value
    override this.Zero() = Euro(0) :> _

最佳答案

您是否尝试将通用约束提升到类级别?

[<AbstractClass>] 
type Currency<'T when 'T :> Currency<'T>>() =
    abstract member Zero : unit -> 'T

type Euro (value: int) =
    inherit Currency<Euro>()
    member this.Value = value
    override this.Zero() = Euro(0)

虽然自引用泛型对我来说总是很奇怪,但这就是它在例如 C# 中的实现方式。

关于f# - 如何正确覆盖受约束的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42253991/

相关文章:

C# 泛型类型约束

c++ - 模板约束是否可用于变量模板?

syntax - `while` 循环在 F# 计算表达式中的作用是什么?

c# - 如何从 C# 调用和处理异步 F# 工作流

recursion - 使用递归和模式匹配从列表中删除元素

f# - 试图理解推断的类型约束

c# - 为什么 MassTransit 消息传递中不允许使用结构?

io - 使用 F# 读取 MNIST 数据集

f# - 为什么 Seq.isEmpty 说没有足够的元素?

scala - 使用类型为编译时检查的任意约束建模