2012-05-21 27 views
2

處理這種情況的正確方法是什麼?我在我的F#類DogTree中有一個方法應該滿足實現兩個接口的Bark()方法的要求。F#兩個接口的顯式接口方法

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" 

回答

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類的額外方法,即用作兩個接口的實現。)

如果您聲明瞭primar Ÿ構造你的類,你可以使用它代替:

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() 
3

這是相當優雅

type TreeDog() = 
    let bark() = printfn "Bark" 
    interface IDog with 
    member this.Bark() = bark() 
    interface ITree with 
    member this.Bark() = bark()