.net - 两个接口(interface)的 F# 显式接口(interface)方法

标签 .net interface f# explicit-interface

处理这种情况的正确方法是什么。我的 F# 类 DogTree 中有一个方法应该满足为两个接口(interface)实现 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" 

最佳答案

您可以委托(delegate)给一个通用的实现:

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 的类中定义了一个额外的方法,用作两个接口(interface)的实现。)

如果你在你的类中声明了一个主构造函数,你可以使用它来代替:

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

关于.net - 两个接口(interface)的 F# 显式接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10678904/

相关文章:

interface - 使用 CaSTLe Windsor 3.0 拦截 Startable 设施调用的方法

java - 如果一个类实现了两个接口(interface),那么哪个是java中该类的实际父接口(interface)

c# - 将文件 any\netstandard1.6\FSharp.Core.sigdata 复制到 obj\Release\Package\PackageTmp\any\netstandard1.6\FSharp.Core.sigdata 失败

c# - .net Framework 4.5 中的日期时间错误

c# - NLog 不写调试消息

.net - 如何从 DataGrid 获取 HTML 输出?

c# - .net4 上的 SHA1 生成

vb.net - 当两个方法同名但参数不同时如何在VB.Net中实现接口(interface)

f# - 不带分号的方括号是什么意思?

validation - F# 使用匹配来验证参数