Bud*_*Joe 2 .net f# interface explicit-interface
处理这种情况的正确方法是什么.我的F#类DogTree中有一个方法应该满足为两个接口实现Bark()方法的要求.
type ITree =
interface
abstract Bark : unit -> unit
abstract Grow : unit -> unit
end
type IDog =
interface
abstract Bark : unit -> unit
abstract ChaseCar : unit -> unit
end
type TreeDog =
// so the "and" syntax below doesn't work - what is the correct way to handle?
interface IDog and ITree with
member this.Bark() = printfn "Bark"
Run Code Online (Sandbox Code Playgroud)
您可以委派一个常见的实现:
type TreeDog =
interface IDog with
member this.Bark() = printfn "Bark"
interface ITree with
member this.Bark() = (this :> IDog).Bark()
Run Code Online (Sandbox Code Playgroud)
或者,更合适:
type TreeDog =
member this.Bark() = printfn "Bark"
interface IDog with
member this.Bark() = this.Bark()
interface ITree with
member this.Bark() = this.Bark()
Run Code Online (Sandbox Code Playgroud)
(注意,这在名为的类中定义了一个额外的方法,Bark用作两个接口的实现.)
如果在类中声明主构造函数,则可以使用它:
type TreeDog() = // primary constructor
let bark() = printfn "Bark" // this member is private
interface IDog with
member this.Bark() = bark()
interface ITree with
member this.Bark() = bark()
Run Code Online (Sandbox Code Playgroud)