Método de interface explícita F# para duas interfaces
-
12-12-2019 - |
Pergunta
Qual é a maneira correta de lidar com esta situação.Eu tenho um método em minha classe F# DogTree que deve atender ao requisito de implementação de um método Bark() para ambas as interfaces.
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"
Solução
Você pode delegar para uma implementação comum:
type TreeDog =
interface IDog with
member this.Bark() = printfn "Bark"
interface ITree with
member this.Bark() = (this :> IDog).Bark()
Ou, mais apropriadamente:
type TreeDog =
member this.Bark() = printfn "Bark"
interface IDog with
member this.Bark() = this.Bark()
interface ITree with
member this.Bark() = this.Bark()
(Observe que isso define um método extra na classe chamado Bark
, que é usado como implementação para ambas as interfaces.)
Se você declarar um construtor primário em sua classe, poderá usar isto:
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()
Outras dicas
Isso é razoavelmente elegante
type TreeDog() =
let bark() = printfn "Bark"
interface IDog with
member this.Bark() = bark()
interface ITree with
member this.Bark() = bark()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow