2

处理这种情况的正确方法是什么。我的 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" 
4

2 回答 2

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()
于 2012-05-21T02:46:02.543 回答
3

这是相当优雅的

type TreeDog() = 
  let bark() = printfn "Bark" 
  interface IDog with
    member this.Bark() = bark()
  interface ITree with
    member this.Bark() = bark()
于 2012-05-21T03:03:23.847 回答