为何实现接口的F#类中,类方法无法调用同类中的另一个方法?
问题:接口实现中MyMethod2无法调用MyMethod1的原因
先看这段报错的F#代码:
type IMyClass = abstract member MyMethod1 : unit -> unit abstract member MyMethod2 : unit -> unit type MyClass() = interface IMyClass with member this.MyMethod1() = printfn "MyMethod1 called" member this.MyMethod2() = printfn "MyMethod2 called" this.MyMethod1()
原因分析
在F#的显式接口实现规则里,接口的成员属于接口类型,而非类本身。这里的this指向的是MyClass的实例,而MyMethod1是IMyClass接口的成员,不是MyClass直接定义的成员——所以直接用this.MyMethod1()会找不到该方法。
而移除接口后的代码能正常运行:
type MyClass() = member this.MyMethod1() = printfn "MyMethod1 called" member this.MyMethod2() = printfn "MyMethod2 called" this.MyMethod1()
这是因为此时MyMethod1是MyClass的直接成员,this作为类实例可以直接访问自身成员,调用自然没问题。
解决方法
要让接口内的MyMethod2能调用MyMethod1,有两种常用方案:
将
this强制转换为接口类型
把类实例转换为接口类型,就能访问接口的成员:type IMyClass = abstract member MyMethod1 : unit -> unit abstract member MyMethod2 : unit -> unit type MyClass() = interface IMyClass with member this.MyMethod1() = printfn "MyMethod1 called" member this.MyMethod2() = printfn "MyMethod2 called" (this :> IMyClass).MyMethod1()类内定义成员,接口实现转发调用
先在类本身定义方法,接口的实现仅转发调用,内部直接访问类成员:type IMyClass = abstract member MyMethod1 : unit -> unit abstract member MyMethod2 : unit -> unit type MyClass() = // 类自身的成员 member this.MyMethod1() = printfn "MyMethod1 called" member this.MyMethod2() = printfn "MyMethod2 called" this.MyMethod1() // 接口实现转发到类成员 interface IMyClass with member this.MyMethod1() = this.MyMethod1() member this.MyMethod2() = this.MyMethod2()
内容的提问来源于stack exchange,提问作者Matthew MacFarland
相关产品推荐
相关产品推荐

