【问题标题】:F# Explicit Interface Method for Two Interfaces两个接口的 F# 显式接口方法
【发布时间】:2012-05-21 02:31:55
【问题描述】:

处理这种情况的正确方法是什么。我的 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" 

【问题讨论】:

    标签: .net interface f# explicit-interface


    【解决方案1】:

    您可以委托给一个通用实现:

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

    【讨论】:

      【解决方案2】:

      这是相当优雅的

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

      【讨论】:

        猜你喜欢
        • 2012-03-23
        • 1970-01-01
        • 2020-12-09
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        • 1970-01-01
        • 1970-01-01
        • 2013-12-01
        相关资源
        最近更新 更多