请考虑以下代码:
Public Class Animal Public Overridable Function Speak() As String Return "Hello" End Function End Class Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function End Class Dim dog As New Dog Dim animal As Animal animal = CType(dog, Animal) // Want "Hello", getting "Ruff" animal.Speak()
如何将Dog的实例转换/ ctype到Animal并让Animal.Speak被调用?
你没有; 子类的方法通过继承的定义覆盖超类的方法.
如果您希望重写的方法可用,请在子类中公开它,例如
Public Class Dog Inherits Animal Public Overrides Function Speak() As String Return "Ruff" End Function Public Function SpeakAsAnimal() As String Return MyBase.Speak() End Function End Class