Domanda

Qual è il modo corretto per gestire questa situazione.Ho un metodo nel mio dogtree di classe F # che dovrebbe soddisfare il requisito di implementare un metodo di abbaiare () per entrambe le interfacce.

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" 
.

È stato utile?

Soluzione

È possibile delegare a un'implementazione comune:

type TreeDog = 
  interface IDog with
    member this.Bark() = printfn "Bark" 
  interface ITree with
    member this.Bark() = (this :> IDog).Bark()
.

o, più appropriatamente:

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

(Si noti che ciò definisce un metodo extra nella classe denominata Bark, che viene utilizzata come implementazione per entrambe le interfacce.)

Se dichiari un costruttore primario nella tua classe, puoi usarlo invece:

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

Altri suggerimenti

Questo è ragionevolmente elegante

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top