VB.NET的預設屬性

來源:互聯網
上載者:User

接受參數的屬性可聲明為類的預設屬性。“預設屬性”是當未給對象命名特定屬性時 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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.