JoeBuntu
Member
- Joined
- Jun 20, 2009
- Messages
- 8
- Programming Experience
- 1-3
What I would like to do is make an abstract class that will hold objects in a dictionary and manage the adding/deleting/key changes of those items in the dictionary. My problem is that in order to make the class as generic as possible I declared the dictionary as dictionary(of long, of SomeInterface).
The problem is when I try to pass a strongly typed dictionary in the constructor using dictionary( of long, ClassThatImplementsSomeInterface) I get a compiler error because it cannot convert to that type.
The reason I want to pass the dictionary in the abstract class's constructor is so that I can use the strongly typed dictionary in the subclass and have the abstract class manage the keys when it needs to. So how can I do something like this? Also- If there is a much better way to manage keys than what I am doing feel free to let me know, but I am much more interested in how to make this work since I have encountered this type of problem a few times before. Thanks alot.
Here's the abstract class:
This is how I am trying to use the subclass
The problem is when I try to pass a strongly typed dictionary in the constructor using dictionary( of long, ClassThatImplementsSomeInterface) I get a compiler error because it cannot convert to that type.
The reason I want to pass the dictionary in the abstract class's constructor is so that I can use the strongly typed dictionary in the subclass and have the abstract class manage the keys when it needs to. So how can I do something like this? Also- If there is a much better way to manage keys than what I am doing feel free to let me know, but I am much more interested in how to make this work since I have encountered this type of problem a few times before. Thanks alot.
Here's the abstract class:
VB.NET:
Public MustInherit Class HasChildrenKeys
Protected m_childItems As Dictionary(Of Long, IHasKey)
Public Sub New(ByVal childItemsDict As Dictionary(Of Long, IHasKey))
m_childItems = childItemsDict
End Sub
Public Sub AddItem(ByVal item As IHasKey)
AddHandler item.KeyChanged, AddressOf ChangeKey
m_childItems.Add(item.Key, item)
End Sub
Public Sub RemoveItem(ByVal item As IHasKey)
RemoveHandler item.KeyChanged, AddressOf ChangeKey
m_childItems.Remove(item.Key)
End Sub
Private Sub ChangeKey(ByVal e As KeyChangeEventArgs)
If m_childItems.ContainsKey(e.OldKey) Then
Dim item = m_childItems.Item(e.OldKey)
Me.RemoveItem(item)
item.Key = e.NewKey
Me.AddItem(item)
End If
End Sub
End Class
This is how I am trying to use the subclass
VB.NET:
Public Class TestClass
Inherits HasChildrenKeys
'BomDetailItem implements IHasKey
Private m_detailItems As New Dictionary(Of Long, BomDetailItem)
Sub New()
'this does not work
'Error: Dictionary(Of Long, BomDetailItem) cannot be converted to
'Dictionary(Of Long, IHasKey)
MyBase.New(m_detailItems)
End Sub
End Class