How can explain the F# type casting output? -
i had problem f# type casting. here code.
type person() = abstract member sayme : unit -> unit default u.sayme() = printfn "hi, person." type student() = inherit person() override u.sayme() = printfn "hi, student." let x = person() let x1 = student() let x2 = x1 :> person x2.sayme()|>ignore //***output:"hi, student."
x2 person type. output should "hi, person."
how can explain it?
as others have noticed, override
syntax defining virtual members.
speaking, calling virtual method seeing: regardless of upcasts, actual method call found according actual type of object referred to, not type of reference.
this document (msdn) provides more details.
if don't want method virtual, don't use override
. way, method in derived class hide parent's method.
here's full code:
type person() = member u.sayme() = printfn "hi, person." type student() = inherit person() member u.sayme() = printfn "hi, student." let x = student() x.sayme() // prints "hi, student." (x :> person).sayme() // prints "hi, person."
Comments
Post a Comment