2009-12-23 2 views
0

classes dans .net comme liste et dictionnaire peuvent être indexés directement, sans mentionner un membre, comme celui-ci:Comment créer une classe pouvant être indexée comme une liste dans .net?

Dim MyList as New List (of integer) 
... 
MyList(5) 'get the sixth element 
MyList.Items(5) 'same thing 

Comment puis-je faire une classe qui peut être indexé comme ça?

Dim c as New MyClass 
... 
c(5) 'get the sixth whatever from c 

Répondre

8

Vous devez fournir un indexeur (C# terminologie) ou propriété par défaut (terminologie VB). Exemple de la MSDN docs:

VB: (myStrings est un tableau de chaînes)

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  

Et C# syntaxe:

public string this[int index] 
{ 
    get { return myStrings[index]; } 
    set { myStrings[index] = vaue; } 
} 
Questions connexes