简体   繁体   中英

Overriding an inherited member in F#

The code below produces "t1 t1 t2". I wondered if someone could please tell me how to change it so as to get "t1 t2 t2". It is an error to use "override" instead of "member" in t2, and I don't understand why. I am more than happy to RTFM, if only I would know where and in what FM to look.

Many thanks in advance, and sorry if I missed some fundamental reason for why what I want should not be possible.

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 ()

This should have the behavior you want:

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 ()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM