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