类方法

更新:2007 年 11 月

类的方法就是在该类中声明的 Sub 或 Function 过程。例如,若要为名为 Account 的类创建 Withdrawal 方法,可以向该类模块中添加此 Public 函数:

Public Function WithDrawal(ByVal Amount As Decimal, _
      ByVal TransactionCode As Byte) As Double
    ' Add code here to perform the withdrawal,
    ' return a transaction code, 
    ' or to raise an overdraft error.
End Function

共享方法

可以直接从类调用共享方法,而不必首先创建该类的实例。当不希望方法与类的特定实例关联时,共享方法很有用。共享方法不能用 Overridable、NotOverridable 或 MustOverride 修饰符声明。模块中声明的方法是隐式共享的,不能显式使用 Shared 修饰符。

示例

Class ShareClass
    Shared Sub SharedSub()
        MsgBox("Shared method.")
    End Sub
End Class

Sub Test()
    ' Call the method.
    ShareClass.SharedSub()
End Sub

保护实现详细信息

某个类在内部使用的实用工具过程应被声明为 Private、Protected 或 Friend。允许您在将来进行更改,而不会影响使用您的对象的代码,从而限制这类方法的可访问性,以保护使用这些对象的开发人员。

保护对象实现的详细信息是“封装”的另一方面。封装使您得以提高方法的性能,或完全改变实现方法的方式,而不必更改使用该方法的代码。

请参见

任务

如何:向类中添加事件

概念

属性与方法

Visual Basic 中的共享成员

参考

Overridable

NotOverridable

MustOverride

Shared (Visual Basic)

Public (Visual Basic)

Private (Visual Basic)

Protected (Visual Basic)

Friend (Visual Basic)