代码之家  ›  专栏  ›  技术社区  ›  Drew Noakes

如何实现在f中返回void的接口成员#

  •  20
  • Drew Noakes  · 技术社区  · 16 年前

    想象一下C中的以下接口:

    interface IFoo {
        void Bar();
    }
    

    我如何在f中实现这一点?我在网上搜索了30分钟后发现的所有示例都只显示具有返回类型的示例,我认为这些类型在函数样式中更常见,但在本例中我无法避免。

    以下是我目前为止的情况:

    type Bar() =
        interface IFoo with
            member this.Bar() =
                void
    

    使用fs0010失败:

    表达式\中出现意外的关键字“void”。

    4 回复  |  直到 10 年前
        1
  •  22
  •   ChaosPandion    16 年前

    等价物是句法上定义为 () .

    type Bar() =
        interface IFoo with
            member this.Bar () = ()
    
        2
  •  7
  •   Drew Noakes    16 年前

    有关F类型的常规信息,请参见

    The basic syntax of F# - types

    从那一页:

    这个 单元 类型只有一个值,写为“()”。这有点像“void”,从某种意义上说,如果您有一个只调用副作用的函数(例如printf),那么这样的函数将有一个返回类型“unit”。每个函数都接受一个参数并返回一个结果,因此使用“Unit”表示该参数/结果是无意义的。

        3
  •  6
  •   corvuscorax    16 年前

    返回类型必须是(),因此 成员this.bar=() 应该做这个把戏

        4
  •  3
  •   Márcio Azevedo    10 年前

    f中的等效值为:

    type IFoo =
        abstract member Bar: unit -> unit