两种接口的F#显式接口方法

时间:2012-05-21 02:31:55

标签: .net interface f# 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" 

2 个答案:

答案 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()