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

时间:2017-08-04 10:11:11

标签: .net f# object-expression

我正在尝试覆盖对象表达式中的类的接口,但是无法访问我正在进行子类化的类的“this”引用。

示例:

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'
   }

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

2 个答案:

答案 0 :(得分:3)

x界面中的IFoo投放到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
}

答案 1 :(得分:2)

您必须在IFoo转换您的访问权限

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