如何使用返回该接口实例的成员来实现 F# 接口?

How to implement an F# interface with a member returing an instance of that interface?

假设我在 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'

要修复类型错误,您需要将返回值显式转换为 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

作为替代品发布并没有更好,只是不同而已:

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

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 }