Inheritance 对象声明为调用子类方法的父类

Inheritance 对象声明为调用子类方法的父类,inheritance,overriding,vb.net-2010,Inheritance,Overriding,Vb.net 2010,有人能解释一下这种行为吗?我有两门课,Foo和BarBar继承Foo并重写其GetVar函数: Public Class Foo Public myVar1 As Integer Public Overridable Function GetVar() As Integer Console.WriteLine("Foo.GetVar!()") Return myVar1 End Function End Class Public Cla

有人能解释一下这种行为吗?我有两门课,
Foo
Bar
Bar
继承
Foo
并重写其
GetVar
函数:

Public Class Foo
    Public myVar1 As Integer

    Public Overridable Function GetVar() As Integer
        Console.WriteLine("Foo.GetVar!()")
        Return myVar1
    End Function
End Class

Public Class Bar
    Inherits Foo

    Public myVar2 As Integer

    Public Overrides Function GetVar() As Integer
        Console.WriteLine("Bar.GetVar!()")
        Return MyBase.GetVar() + myVar2
    End Function

End Class
在我的
main()
模块中,发生以下情况:

Sub Main()
    Dim myBar As New Bar
    myBar.myVar1 = 2
    myBar.myVar2 = 2

    Dim myFoo As Foo
    myFoo = myBar

    Console.WriteLine(myFoo.GetVar())

    Console.ReadKey()
End Sub
输出为:

Bar.GetVar()!
Foo.GetVar()!
4

这对我来说似乎很奇怪-
myFoo
被声明为类型为
Foo
的对象,所以我认为调用
myFoo.GetVar()
会调用
Foo
GetVar()
(输出2)实现,而不会显式地向下转换它,我认为
myFoo
实际上是一个
Bar
的事实会因为它的
Foo
声明而“不可见”。为什么会发生这种情况?

我明白了
myFoo.getVar()
myFoo
指向的对象调用
getVar()
。虽然它不知道所说的对象是一个
Bar
(并且不能访问
Bar
专有的东西,比如
myVar2
),但它仍然是一个
Bar
,它在那里启动自己的
getVar()
函数

我肯定这种行为有个名字,但我不记得了。有人要吗