【问题标题】:How to implement an F# interface with a member returing an instance of that interface?如何使用返回该接口实例的成员实现 F# 接口?
【发布时间】:2022-01-13 11:15:33
【问题描述】:

假设我在 F# 中有以下界面:

type InterfaceA =
 abstract Magic : InterfaceA -> InterfaceA

如何实现这样的接口? 当我尝试这样做时:

type MyTypeA = {x:int} with
 interface InterfaceA with
  member self.Magic another = 
   {x=self.x+another.x}

我收到错误: This expression was expected to have type 'InterfaceA' but here has type 'MyTypeA'

【问题讨论】:

    标签: interface f# interface-implementation


    【解决方案1】:

    发帖作为替代方案,并不是真的更好,只是不同:

    从 F# 6 开始,您还可以注释返回类型,编译器会推断您的意思:

    type InterfaceA =
     abstract Magic : InterfaceA -> InterfaceA
     abstract Value : int
    
    type MyTypeA = 
      {x:int} 
      interface InterfaceA with
        member self.Value = self.x
        member self.Magic another : InterfaceA = 
          { x=self.x+another.Value }
    

    【讨论】:

      【解决方案2】:

      要修复类型错误,您需要将返回值显式转换为 InterfaceA 类型 - 与 C# 不同,F# 不会自动执行此操作:

      type InterfaceA =
       abstract Magic : InterfaceA -> InterfaceA
       abstract Value : int
      
      type MyTypeA = 
        {x:int} 
        interface InterfaceA with
          member self.Value = self.x
          member self.Magic another = 
            { x=self.x+another.Value } :> InterfaceA
      

      请注意,您的代码也不起作用,因为 another 的类型为 InterfaceA,因此它没有您可以访问的 x 字段。为了解决这个问题,我在界面中添加了一个成员 Value

      【讨论】:

      • 请注意,您可以在转换中省略接口名称以使其更短:{ x=self.x+another.Value } :> _。编译器将推断出正确的类型。此外,在 F# 6 中根本不需要这个演员表。
      猜你喜欢
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      相关资源
      最近更新 更多