处理这种情况的正确方法是什么。我的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"
答案 0 :(得分:6)
您可以委派一个常见的实现:
type TreeDog =
interface IDog with
member this.Bark() = printfn "Bark"
interface ITree with
member this.Bark() = (this :> IDog).Bark()
或者,更合适:
type TreeDog =
member this.Bark() = printfn "Bark"
interface IDog with
member this.Bark() = this.Bark()
interface ITree with
member this.Bark() = this.Bark()
(请注意,这在名为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()
答案 1 :(得分:3)
这是相当优雅的
type TreeDog() =
let bark() = printfn "Bark"
interface IDog with
member this.Bark() = bark()
interface ITree with
member this.Bark() = bark()