【问题标题】:Passing "unit" as type parameter to generic class in F#将“单元”作为类型参数传递给 F# 中的泛型类
【发布时间】:2017-12-20 15:55:25
【问题描述】:

我有一个接口,它接受一个泛型参数并有一个抽象方法

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

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

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

但编译器抱怨说

错误成员 'abstractMethod : unit -> unit' 没有 正确的类型来覆盖相应的抽象方法。

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

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

谢谢!

【问题讨论】:

  • 您对 abstractMethod 的覆盖没有签名 unit -&gt; unit--它采用未指定类型的参数(名为 _)。
  • 查看stackoverflow.com/questions/40283165/… 以及从那里链接的其他问题。

标签: f#


【解决方案1】:

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

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

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#)

【讨论】:

    猜你喜欢
    • 2019-02-27
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多