[VB.NET]VB 10.0 Auto-Implemented Properties
Property Name As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property</pre></div><p> </p><p>透過VB.NET 10.0的Auto-Implemented Properties功能,我們可以將屬性的撰寫給簡化。像是上面的例子可簡化為像下面這樣:</p><div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:636f2abe-f420-46bd-a9e4-5ced6d93ac70" class="wlWriterEditableSmartContent"><pre class="vb:nocontrols" name="code">
Property Name As String 短短的一行就可以取代本來冗長的程式,是不是很方便呢?除此之外,Auto-Implemented Properties也可以利用變數初始器來設定屬性的預設值。就像: Property Name As String = “Larry” 若是使用較為複雜的型別也可以 Property SupplierList() As New List(Of Supplier) Property OrderList() As New List(Of Order) With {.Capacity = 100} 也可以用在介面屬性的實作上 Property Name() As String Implements ICustomer.Name 注意事項1.不支援ReadOnly關鍵字若在Auto-Implemented Properties前面加上ReadOnly關鍵字 ReadOnly Property Name() As String 則編譯器會顯示錯誤 2.不支援WriteOnly關鍵字若在Auto-Implemented Properties前面加上WriteOnly關鍵字 WriteOnly Property Name() As String 則編譯器會顯示錯誤 3.不支援帶參數的屬性若在Auto-Implemented Properties設定參數 Property Items(ByVal idx As Integer) As String 則編譯器會顯示錯誤 4.不支援索引器由於無法支援帶參數的屬性,自然無法支援索引器。