[英]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.