如何使用重写的抽象成员的基本实现?
How to use the base implementation of an overridden abstract member?
有一个接口(比如 IA),接口 IA 的一个实现(比如 Base),以及 Base 的派生 class(比如 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)
其实我觉得没有办法做到这一点。 F# 接口实现类似于 C# 中的 显式接口实现 和 you cannot call base implementation of an explicitly implemented interface in C#.
解决方法是修改基础class,使其更像 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
下面现在 returns 3 符合预期:
(Derived() :> IA).A
有一个接口(比如 IA),接口 IA 的一个实现(比如 Base),以及 Base 的派生 class(比如 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)
其实我觉得没有办法做到这一点。 F# 接口实现类似于 C# 中的 显式接口实现 和 you cannot call base implementation of an explicitly implemented interface in C#.
解决方法是修改基础class,使其更像 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
下面现在 returns 3 符合预期:
(Derived() :> IA).A