覆盖F#中的继承成员

时间:2012-08-04 21:53:48

标签: f#

以下代码生成“t1 t1 t2”。我想知道是否有人可以告诉我如何更改它以获得“t1 t2 t2”。在t2中使用“覆盖”而不是“成员”是错误的,我不明白为什么。我对RTFM感到非常高兴,只要我知道FM的外观和内容。

非常感谢,如果我错过了为什么我想要的东西不可能的一些根本原因,那就很抱歉。

type myinterface =
   abstract member doit : unit -> unit

type t1 () =
   interface myinterface with
      member x.doit () = printf "t1\n"

type t2 () =
    inherit t1 ()

    member x.doit () = printf "t2\n"

let override_test () =
    let t1 = t1 () :> myinterface
    let t2 = t2 ()
    let t2i = t2 :> myinterface
    t1.doit ()
    t2i.doit ()
    t2.doit ()

1 个答案:

答案 0 :(得分:5)

这应该有你想要的行为:

type myinterface =
    abstract member doit : unit -> unit

type T1 () =
    interface myinterface with
        member x.doit () = printfn "t1"

type T2 () =
    inherit T1 ()
    member x.doit () = printfn "t2"
    interface myinterface with
        member x.doit () = x.doit ()

let override_test () =
    let t1i = T1() :> myinterface
    let t2 = T2()
    let t2i = t2 :> myinterface
    t1i.doit ()
    t2i.doit ()
    t2.doit ()