【问题标题】:Implementing Interfaces Explictly in F#在 F# 中显式实现接口
【发布时间】:2012-05-05 11:31:19
【问题描述】:

好的,C# 有Explictit Interface Implementation 我想在 F# 中做类似的事情。

我有一些接口(和类)

type IState = interface
    abstract member Update : IAction-> IState
    ...
end
type IEnviroment = interface
    abstract member Update : IAction-> IEnviroment
    ...
    end


type IBoard  = 
    inherit IState
    inherit IEnviroment
    abstract member Update : Move -> IBoard
    ...

[<AbstractClass>]
and Move ()= 
    abstract member Apply : IBoard -> IBoard
    interface IAction with        
        override this.Cost = 1M

所以我遇到的问题是更新的定义有 3 次不同。 所以我需要C#的Explictit Interface Implementation, 我想我会在接口中实现它(因为这在 F# 中是合法的)——它只包含一些类型转换。

我的理解是 F# 中的所有接口实现都是显式的,在类中, 但是一旦一个接口继承自另一个接口,那么你就只能(显式地)实现那个接口。 (所以我的 Board 类只实现了 I Board)

【问题讨论】:

  • 不能重命名方法吗?我认为让三个同名的方法在一个接口中做不同的事情是令人困惑的。它也能解决你的问题。
  • 实际上他们都做同样的事情(甚至在相同的对象上)。它只是接口提供/需要的其他东西是不同的。他们出于不同的目的做同样的事情

标签: .net interface f# explicit-interface explicit-implementation


【解决方案1】:

我在IBoard的实现中尝试了member this.IState.Update的语法,但是编译器拒绝了。

我在spec 中看不到做你想做的事的方法。

这是一种解决此类名称冲突的方法,使用抽象类将调用转发到每个接口。

type I1 =
    interface
        abstract F : unit -> unit
    end

type I2 =
    interface
        abstract F : unit -> unit
    end

type II =
    interface
        inherit I1
        inherit I2
        abstract F : unit -> unit
    end

[<AbstractClass>]
type III() =
    abstract F1 : unit -> unit
    abstract F2 : unit -> unit
    abstract F3 : unit -> unit
    interface I1 with
        member this.F() = this.F1()
    interface I2 with
        member this.F() = this.F2()

type Works() =
    inherit III()
    override this.F1() = printfn "F1"
    override this.F2() = printfn "F2"
    override this.F3() = printfn "F3"

type Fails() =
    interface II with
        member this.F() = ()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多