gpt4 book ai didi

vb.net - 从子实例调用被覆盖的基类方法

转载 作者:行者123 更新时间:2023-12-04 06:14:03 24 4
gpt4 key购买 nike

考虑以下代码:

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?

最佳答案

你没有;根据继承的定义,子类的方法覆盖父类(super class)的方法。

如果您希望覆盖的方法可用,请在子类中公开它,例如

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

关于vb.net - 从子实例调用被覆盖的基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/244886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com