如何使用重写的抽象成员的基本实现?

时间:2016-06-03 13:09:45

标签: f# abstract member override

有一个接口(比如IA),一个接口IA的实现(比如Base),以及一个派生类Base(比如Derived),它覆盖了IA的抽象成员。现在,在重写成员的实现中,我想使用Base的成员的实现。但是,我不知道怎么写这样做。

此代码说明了我的问题:

type Flag =
  | F1 = 1
  | F2 = 2

type IA =
  abstract member A: Flag

type Base() =
  interface IA with
    member this.A = F1

type Derived() =
  inherit Base()

  interface IA with
    override this.A = (* ? *)
      // base.A ||| F2             // NG (Compile error that `A` isn't a member of `base`)
      // (base :> IA).A ||| F2     // NG (Syntax error)
      // (this :> IA).A ||| F2     // NG (Infinite recursion)

1 个答案:

答案 0 :(得分:6)

我实际上认为没有办法做到这一点。 F#接口实现类似于C#和you cannot call base implementation of an explicitly implemented interface in C#中的显式接口实现

解决方法是修改基类,使其更像C#隐式接口实现(遗憾的是有点麻烦):

type Base() =
  // Define virtual property in class Base
  abstract A : Flag
  default this.A = Flag.F1
  // Implement IA via the virtual property
  interface IA with
    member this.A = this.A

type Derived() =
  inherit Base() 
  // Override the virtual property
  override this.A = base.A ||| Flag.F2

以下现在按预期返回3:

(Derived() :> IA).A