如何在成员返回F#接口实例的情况下实现该接口



假设我在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开始,您还可以注释返回类型,编译器将推断出您的意思:

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 }

最新更新