f# - 将 "unit"作为类型参数传递给 F# 中的泛型类

标签 f#

我有一个接口(interface),它采用通用参数并具有抽象方法

type MyInterface<'a> =
    abstract member abstractMethod: 'a -> 'a

...我有一个派生类,它使用 unit 作为类型参数从基类继承

type Derived() =
    interface MyInterface<unit> with
        override this.abstractMethod (_) = ()

但是编译器提示

Error The member 'abstractMethod : unit -> unit' does not have the correct type to override the corresponding abstract method.

如果我使用其他类型而不是单位,例如 int,代码将编译。

这是编译器中的错误吗?有解决办法吗?

谢谢!

最佳答案

unit 在互操作方面是“特殊”的:当函数采用 unit 作为参数时,它会作为无参数函数编译为 IL,而当函数采用 unit 作为参数时,它会被编译为 IL返回一个 unit 作为结果,它被编译为 void 函数。由于这种欺骗,您无法真正将 unit 用作互操作设置(例如类和接口(interface))中的“通用”类型。

事实上,当我尝试在我的机器上编译您的代码时,我收到了不同的错误:

The member 'abstractMethod : unit -> unit' is specialized with 'unit' 
but 'unit' can't be used as return type of an abstract method
parameterized on return type.

这试图粗略地表达我上面所描述的内容。

(我不确定您为什么会得到这样的结果;也许您使用的是旧版本的 F#)

关于f# - 将 "unit"作为类型参数传递给 F# 中的泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47909938/

相关文章:

algorithm - 使用 F# 实现树生成器

f# - F# 中的命名空间别名?

.net - Gmail API .NET : How to request messages from one sender

f# - 如何解析重复模式之后正确的时间之间的关系?

mongodb - 是否可以向 MongoDB 写入可区分的联合?

F# 函数调用无法正常工作

wpf - F# WPF - 在 Viewport3D 中显示简单对象

f# - 我如何在 F# 中执行 APL 中的压缩?

f# - 在 F# 中,为什么空格会影响此代码

f# - 我怎样才能摆脱这个 "Can not be generalised"错误?