[英]F# Explicit Interface Method for Two Interfaces
處理這種情況的正確方法是什么。 我的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"
您可以委派一個常見的實現:
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()
這相當優雅
type TreeDog() =
let bark() = printfn "Bark"
interface IDog with
member this.Bark() = bark()
interface ITree with
member this.Bark() = bark()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.