默认属性

更新:2007 年 11 月

接受参数的属性可声明为类的默认属性。当未给对象指定具体的属性时,“默认属性”是 Visual Basic 将使用的属性。因为默认属性使您得以通过省略常用属性名使源代码更为精简,所以默认属性非常有用。

最适宜作为默认属性的是那些接受参数并且您认为将最常用的属性。例如,Item 属性就非常适合作为集合类的默认属性,因为它经常被使用。

下列规则适用于默认属性:

  • 一种类型只能有一个默认属性,包括从基类继承的属性。此规则有一个例外。在基类中定义的默认属性可以被派生类中的另一个默认属性隐藏。

  • 如果基类中的默认属性被派生类中的非默认属性隐藏,使用默认属性语法仍可以访问该默认属性。

  • 默认属性不能为 Shared 或 Private。

  • 如果某个重载属性是默认属性,则同名的所有重载属性必须也指定 Default。

  • 默认属性必须至少接受一个参数。

示例

下面的示例将一个包含字符串数组的属性声明为类的默认属性:

Class Class2
    ' Define a local variable to store the property value.
    Private PropertyValues As String()
    ' Define the default property.
    Default Public Property Prop1(ByVal Index As Integer) As String
        Get
            Return PropertyValues(Index)
        End Get
        Set(ByVal Value As String)
            If PropertyValues Is Nothing Then
                ' The array contains Nothing when first accessed.
                ReDim PropertyValues(0)
            Else
                ' Re-dimension the array to hold the new element.
                ReDim Preserve PropertyValues(UBound(PropertyValues) + 1)
            End If
            PropertyValues(Index) = Value
        End Set
    End Property
End Class

访问默认属性

可以使用缩写语法访问默认属性。例如,下面的代码片段同时使用标准和默认属性语法:

Dim C As New Class2
' The first two lines of code access a property the standard way.

' Property assignment.
C.Prop1(0) = "Value One"
' Property retrieval.
MsgBox(C.Prop1(0))

' The following two lines of code use default property syntax.

' Property assignment.
C(1) = "Value Two"
' Property retrieval.
MsgBox(C(1))

请参见

概念

升级建议:解析无参数默认属性

默认属性更改(针对 Visual Basic 6.0 用户)

参考

Default (Visual Basic)