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