我正在尝试覆盖对象表达式中的类的接口,但是无法访问我正在进行子类化的类的“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'
}
奖金问题:我可以以某种方式摆脱虚拟覆盖吗?
答案 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 ()
}