< Day Day Up > |
A property is a cross between a field and a method. From the outside, a property looks and behaves like a field. But on the inside, there is not necessarily a variable storing the property's value. Instead, the property provides methods to get and set the value, called accessors . The accessors can deal with the value of the property in any way they see fit. The following example defines a Total property that calculates the Order total by multiplying Cost by Quantity . When the property is used, however, it appears just to be a field of the Order class. Class Order Public Cost As Double Public Quantity As Integer Public ReadOnly Property Total() As Double Get Return Cost * Quantity End Get End Property End Class Module Test Sub Main() Dim Order As Order = New Order() Order.Cost = 34.32 Order.Quantity = 5 Console.WriteLine(Order.Total) End Sub End Module Properties can also have parameters; such properties are called indexed properties because the arguments are specified like array indexes. The following example defines a simple collection class that stores orders. When the Main subroutine fetches orders from the collection, it provides an index just as if the collection were an array. Class Order Public Cost As Double Public Quantity As Integer End Class Class OrderCollection Private _Orders(9) As Order Public Property Orders(ByVal Index As Integer) As Order Get If _Orders(Index) Is Nothing Then _Orders(Index) = New Order() End If Return _Orders(Index) End Get Set (Value As Order) _Orders(Index) = Value End Set End Property End Class Module Test Sub Main() Dim OrderCollection As New OrderCollection() OrderCollection.Orders(5).Cost = 10.34 Console.WriteLine(OrderCollection.Orders(5).Cost) End Sub End Module An indexed property can be declared as the default property for the type. This allows the type itself to be indexed directly as if it were the default property. In the following example, when the index is applied to the Customers variable, it is equivalent to applying the index to the default property of the CustomerCollection class. Class Customer Public Name As String End Class Class CustomerCollection Private _Customers(9) As Customer Public Default Property Customer(ByVal Index As Integer) As Customer Get If _Customers(Index) Is Nothing Then _Customers(Index) = New Customer() End If Return _Customers(Index) End Get Set (Value As Customer) _Customers(Index) = Value End Set End Property End Class Module Test Sub Main() Dim Customers As New CustomerCollection() ' Customers(5).Name is equivalent to Customers.Customer(5).Name Customers(5).Name = "John Doe" Console.WriteLine(Customers(5).Name) End Sub End Module Default properties are most useful for defining collection types that work like arrays. |
< Day Day Up > |