在什么情况下,使用VB.NET中的MyBase和MyClass关键字?
当虚拟函数需要调用其父版本时,使用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#中的基数相同)
MyClass很少使用。它调用自己的类的方法,即使它通常调用派生类的虚方法。换句话说,它解散虚拟方法调度,而是进行静态调用。
这是一个有创意的例子。现在我很难找到一个现实世界的用法(尽管当然存在):
- 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中,这会发出一个调用而不是通常的callvirt操作码)