问题描述
在什么情况下会在 VB.NET 中使用 MyBase
和 MyClass
关键字?
In what scenarios would one use the MyBase
and MyClass
keywords in VB.NET?
推荐答案
MyBase
用于虚函数需要调用其父版本的时候.例如,考虑:
MyBase
is used when a virtual function needs to call its parent’s version. For example, consider:
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
相同.)
(This is the same as base
in C#.)
MyClass
很少使用.它调用自己类的方法,即使它通常会调用派生类的虚方法.换句话说,它解散了虚拟方法调度,而是进行静态调用.
MyClass
is rarely used at all. It calls the own class’s method, even if it would usually call the derived class’s virtual method. In other words, it disbands the virtual method dispatching and instead makes a static call.
这是一个人为的例子.我现在很难找到现实世界的用法(尽管确实存在):
This is a contrived example. I’m hard-pressed to find a real-world usage now (although that certainly exists):
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
操作码.)
(This doesn’t exist in C#. In IL, this issues a call
instead of the usual callvirt
opcode.)
这篇关于“我的基地"和“我的课堂"在 VB.NET 中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!