当重写派生类中的方法时,可以使用 MyBase 关键字调用基类中的方法。例如,假设您正在设计一个重写从基类继承的方法的派生类。重写的方法可以调用基类中的该方法,并修改返回值,如下面的代码片段中所示:
Class DerivedClass
Inherits BaseClass
Public Overrides Function CalculateShipping(ByVal Dist As Double, _
ByVal Rate As Double) As Double
' Call the method in the base class and modify the return value.
Return MyBase.CalculateShipping(Dist, Rate) * 2
End Function
End Class
下面的列表描述对使用 MyBase 的限制:
Me关键字
通过 Me 关键字,可以引用当前在其中执行代码的类或结构的特定实例。Me 的行为与引用当前实例的对象变量或结构变量类似。在向另一个类、结构或模块中的过程传递关于某个类或结构的当前执行实例的信息时,使用 Me 尤其有用。例如,假定在某模块中有以下过程:
Sub ChangeFormColor(FormName As Form)
Randomize()
FormName.BackColor = Color.FromArgb(Rnd() * 256, Rnd() * 256, Rnd() * 256)
End Sub
可以使用以下语句来调用此过程并将“窗体”(Form) 类的当前实例作为参数传递:
ChangeFormColor(Me)
通过 Me 关键字,可以引用当前在其中执行代码的类或结构的特定实例。Me 的行为与引用当前实例的对象变量或结构变量类似。在向另一个类、结构或模块中的过程传递关于某个类或结构的当前执行实例的信息时,使用 Me 尤其有用。例如,假定在某模块中有以下过程:
Sub ChangeFormColor(FormName As Form)
Randomize()
FormName.BackColor = Color.FromArgb(Rnd() * 256, Rnd() * 256, Rnd() * 256)
End Sub
可以使用以下语句来调用此过程并将“窗体”(Form) 类的当前实例作为参数传递:
ChangeFormColor(Me)
Class DerivedClass
Inherits BaseClass
Public Overrides Function CalculateShipping(ByVal Dist As Double, _
ByVal Rate As Double) As Double
' Call the method in the base class and modify the return value.
Return MyBase.CalculateShipping(Dist, Rate) * 2
End Function
End Class
下面的列表描述对使用 MyBase 的限制: