我有一个接口(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/