如何实现 F# 接口并让成员返回该接口的实例?

zaj*_*jer 1 f# interface interface-implementation

假设我在 F# 中有以下接口:

type InterfaceA =
 abstract Magic : InterfaceA -> InterfaceA
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现这样的接口?当我尝试这样做时:

type MyTypeA = {x:int} with
 interface InterfaceA with
  member self.Magic another = 
   {x=self.x+another.x}
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*cek 7

要修复类型错误,您需要将返回值显式转换为类型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
Run Code Online (Sandbox Code Playgroud)

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