VB.NET默認屬性適用規則介紹
VB.NET編程語言的出現,幫助開發人員輕松的實現了許多功能,我們可以利用它來幫助我們提高編程效率。在VB.NET中,接受參數的屬性可聲明為類的VB.NET默認屬性。“默認屬性”是當未給對象命名特定屬性時 Microsoft Visual Basic .NET 將使用的屬性。因為默認屬性使您得以通過省略常用屬性名使源代碼更為精簡,所以默認屬性非常有用。#t#
最適宜作為默認屬性的是那些接受參數并且您認為將最常用的屬性。例如,Item 屬性就是集合類默認屬性的很好的選擇,因為它被經常使用。
下列規則適用于VB.NET默認屬性:
一種類型只能有一個默認屬性,包括從基類繼承的屬性。此規則有一個例外。在基類中定義的默認屬性可以被派生類中的另一個默認屬性隱藏。
如果基類中的默認屬性被派生類中的非默認屬性隱藏,使用默認屬性語法仍可以訪問該默認屬性。
默認屬性不能是 Shared 或 Private。
如果某個重載屬性是VB.NET默認屬性,則同名的所有重載屬性必須也指定 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
訪問VB.NET默認屬性
可以使用縮寫語法訪問默認屬性。例如,下面的代碼片段同時使用標準和VB.NET默認屬性語法:
- 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.