Skip to content

Protected

声明可从声明类的内部和通过Inherits派生的类中访问的类成员(变量、过程或属性),但外部调用者不能访问。

INFO

Protected访问修饰符是twinBASIC对经典VBA的扩展,VBA只有PublicPrivateFriendProtected仅在Inherits层次结构中有意义;在没有继承的类中,其行为类似于Private

语法:

  • Protected varname [ ( [ subscripts ] ) ] [ As [ New ] type ] [ , varname ... ]

  • Protected [ Overridable ] Sub | Function | Property Get | Property Let | Property Set name ...

在变量声明中,Protected的形式与Private/Public相同:逗号分隔的名称列表,带有可选的WithEvents/NewAs子句。Protected仅在类作用域中有效;不能在过程内部使用(请使用DimStatic),也不能在Module中使用(模块没有派生类型的概念)。

在过程声明中,Protected替换Public/Private/Friend修饰符。与Overridable关键字组合使用,它声明一个继承钩子——派生类允许覆盖的方法或属性。

可见性摘要

修饰符同一类派生类(通过Inherits其他代码
Public
Friend仅在项目内
Protected
Private

示例

以下模式使用Protected状态加上Overridable Protected方法作为继承钩子。基类Animal公开一个公共的Speak,委托给GetSound,派生类覆盖它:

vb
Private Class Animal
    Protected _name As String
    Protected _dob As Date  ' date of birth

    Public Sub New(name As String, dob As Date)
        _name = name
        _dob = dob
    End Sub

    Public Property Get Name() As String
        Name = _name
    End Property

    Public Sub Speak()
        Debug.Print _name & " says: " & GetSound()
    End Sub

    ' Overridable hook for derived classes.
    Protected Overridable Function GetSound() As String
        GetSound = ""
    End Function
End Class

Private Class Dog
    Inherits Animal

    Public Sub New(name As String, dob As Date)
        Animal.New(name, dob)               ' explicit base constructor call
    End Sub

    Protected Function GetSound() As String Overrides Animal.GetSound
        GetSound = "woof"
    End Function
End Class

_name_dobDog内部可见(因为Dog继承自Animal),但对于从层次结构外部持有AnimalDog引用的任何代码不可见。

另请参阅

twinBASIC及其LOGO版权为作者"韦恩"所有