gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:39:35 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com