接受参数的属性可声明为类的默认属性。“默认属性”是当未给对象命名特定属性时 Microsoft Visual Basic .NET 将使用的属性。因为默认属性使您得以通过省略常用属性名使源代码更为精简,所以默认属性非常有用。 最适宜作为默认属性的是那些接受参数并且您认为将最常用的属性。例如,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. C.Prop1(0) = "Value One" ' Property assignment. MessageBox.Show(C.Prop1(0)) ' Property retrieval.
' The following two lines of code use default property syntax. C(1) = "Value Two" ' Property assignment. MessageBox.Show(C(1)) ' Property retrieval.
|