F#upcasting base

时间:2013-02-22 21:25:16

标签: f# f#-3.0 upcasting

当我想将base向上转换为适当的接口类型(即A)时,我得到一个解析错误,这样我就可以在其上调用doA()。我知道basehttp://cs.hubfs.net/topic/None/58670)有点特别,但到目前为止我还没能找到解决这个问题的方法。

有什么建议吗?

type A =
    abstract member doA : unit -> string

type ConcreteA() =
    interface A with
        member this.doA() = "a"

type ExtA() = 
    inherit ConcreteA()


interface A with
    override this.doA() = "ex" // + (base :> A).doA() -> parse error (unexpected symbol ':>' in expression)

((new ExtA()) :> A).doA() // output: ex

工作的C#等价物:

public interface A
{
    string doA();
}

public class ConcreteA : A {
    public virtual string doA() { return "a"; }
}

public class ExtA : ConcreteA {
    public override string doA() { return "ex" + base.doA(); }
}

new ExtA().doA(); // output: exa

1 个答案:

答案 0 :(得分:6)

这相当于你的C#:

type A =
    abstract member doA : unit -> string

type ConcreteA() =
    abstract doA : unit -> string
    default this.doA() = "a"
    interface A with
        member this.doA() = this.doA()

type ExtA() = 
    inherit ConcreteA()
    override this.doA() = "ex" + base.doA()

ExtA().doA() // output: exa

base不能单独使用,仅用于成员访问(因此解析错误)。请参阅Classes on MSDN下的指定继承