对象表达式接口部分的对象引用

Object reference in interface part of object expression

我正在尝试覆盖对象表达式中 class 的接口,但无法访问 class 的 'this' 引用我是 subclassing.

示例:

type IFoo =
    abstract member DoIt: unit -> unit

type Foo () =
    member x.SayHey () = printfn "Hey!"
    member x.SayBye () = printfn "Bye!"
    interface IFoo with
        member x.DoIt () = x.SayHey () // x is 'Foo'


let foo =
   {
     new Foo () with
        // Dummy since F# won't allow object expression with no overrides / abstract implementations
        override x.ToString () = base.ToString () 
     interface IFoo with
        member x.DoIt () = x.SayBye () // Error: x is 'IFoo'
   }

奖金问题:我能以某种方式摆脱那个虚拟覆盖吗?

您必须在 IFoo 中设置您的访问权限,以便

let foo =
    {
         new Foo () with
             override x.ToString () = base.ToString () 
         interface IFoo with
             member x.DoIt () = (x :?> Foo).SayBye () 
    }

IFoo 界面中的 x 转换为 Foo 类型:

let foo =
{
    new Foo () with
        // Dummy since F# won't allow object expression with no overrides / abstract implementations
        override x.ToString () = base.ToString () 
    interface IFoo with
        member x.DoIt () = (x :?> Foo).SayBye () // No type error
}