有人可以解释这种行为吗?我有两个班,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
被声明为 type 的对象Foo
,所以我认为调用myFoo.GetVar()
会调用(输出 2)Foo
的实现GetVar()
- 没有明确地向下转换它,我认为实际上myFoo
是 a的事实Bar
将是“不可见的”由于它的Foo
声明。为什么会这样?