How do I make a class that can be indexed like a list in .net?
Classes in .net like List and Dictionary can be indexed directly, without mentioning a member, like this:
Dim MyList as New List (of integer)
...
MyList(5) 'get the sixth elemen开发者_JAVA百科t
MyList.Items(5) 'same thing
How do I make a class that can be indexed like that?
Dim c as New MyClass
...
c(5) 'get the sixth whatever from c
You need to provide an indexer (C# terminology) or default property (VB terminology). Example from the MSDN docs:
VB: (myStrings
is a string array)
Default Property myProperty(ByVal index As Integer) As String
Get
' The Get property procedure is called when the value
' of the property is retrieved.
Return myStrings(index)
End Get
Set(ByVal Value As String)
' The Set property procedure is called when the value
' of the property is modified.
' The value to be assigned is passed in the argument
' to Set.
myStrings(index) = Value
End Set
End Property
And C# syntax:
public string this[int index]
{
get { return myStrings[index]; }
set { myStrings[index] = vaue; }
}
精彩评论