Criando coleções personalizadas com par Nome/Objeto

Quando desejamos criar coleções personalizadas normalmente criamos uma classe personalizada herdando de CollectionBase . Porém a collectionBase cria coleções apenas indexadas, não permite que utilizemos um par Key/Valor

Para utilizarmos isso deveremos fazer a herança de outra classe base: NameObjectCollectionBase.

 

Exemplo:

 

Public Class NameObjectCollection

Inherits System.Collections.Specialized.NameObjectCollectionBase

 

Sub Add(ByVal key As String, ByVal obj As Object)

Me.BaseAdd(key, obj)

End Sub

 

Sub Clear()

Me.BaseClear()

End Sub

 

The Remove method overload that takes a string key

Sub Remove(ByVal key As String)

Me.Remove(key)

End Sub

 

The Remove method overload that takes a numeric index

Sub Remove(ByVal index As Integer)

Me.Remove(index)

End Sub

 

The Item property overload that takes a string key

Default Property Item(ByVal key As String) As Object

Get

Return Me.BaseGet(key)

End Get

Set(ByVal Value As Object)

Me.BaseSet(key, Value)

End Set

End Property

 

The Item property overload that takes a numeric index

Default Property Item(ByVal index As Integer) As Object

Get

Return Me.BaseGet(index)

End Get

Set(ByVal Value As Object)

Me.BaseSet(index, Value)

End Set

End Property

End Class

  

Dim col As New NameObjectCollection

col.Add("one", 1)

col.Add("two", 2)

col.Add("three", 3)

 

visit elements by their index

For i As Integer = 0 To col.Count - 1

Console.WriteLine("col() = ", i, col(i))

Next

 

visit elements by their key

For Each key As String In col

Console.WriteLine("col() = ", key, col(key))

Next