gpt4 book ai didi

vb.net - "MyBase"和 "MyClass"在 VB.NET 中的用法

转载 作者:行者123 更新时间:2023-12-01 23:52:54 26 4
gpt4 key购买 nike

在什么情况下会在 VB.NET 中使用 MyBaseMyClass 关键字?

最佳答案

当虚拟函数需要调用其父版本时,使用

MyBase。例如,考虑:

Class Button
Public Overridable Sub Paint()
' Paint button here. '
End Sub
End Class

Class ButtonWithFancyBanner
Inherits Button

Public Overrides Sub Paint()
' First, paint the button. '
MyBase.Paint()
' Now, paint the banner. … '
End Sub
End Class

(这与 C# 中的 base 相同。)

<小时/>

MyClass 很少使用。它调用自己的类的方法,即使它通常会调用派生类的虚拟方法。换句话说,它取消了虚拟方法分派(dispatch),而是进行静态调用。

这是一个人为的例子。我现在很难找到现实世界的用法(尽管确实存在):

Class Base
Public Overridable Sub PrintName()
Console.WriteLine("I’m Base")
End Sub

Public Sub ReallyPrintMyName()
MyClass.PrintName()
End Sub
End Class

Class Derived
Inherits Base
Public Overrides Sub PrintName()
Console.WriteLine("I’m Derived")
End Sub
End Class

' … Usage: '

Dim b As Base = New Derived()
b.PrintName() ' Prints "I’m Derived" '
b.ReallyPrintMyName() ' Prints "I’m Base" '

(这在 C# 中不存在。在 IL 中,这会发出 call 而不是通常的 callvirt 操作码。)

关于vb.net - "MyBase"和 "MyClass"在 VB.NET 中的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2849329/

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