I created a Class that inherits List(Of TKey, TValue)
and adds a few functions. Its purpose is not to add items to it at runtime, but when it is initialized. I would actually like to remove the add/delete methods from the class (as it currently exposes them from the inherited class).
If you see the TestApp
Class you will see, if I add a List(Of String, Integer)
to the class it works just fine. However, in the provided code below, when I try to use Me.Add()
in the class constructor; to add a it does not work. It actually tells me that a String cannot be converted to TKey and an Integer cannot be converted to a TValue. Which is untrue! It works fine in the test app.
Any ideas? Here is the code. Two classes, the Vars class and a Test app.
Note: Even using the Overrides Add
method from within the class, as Me.Add(String, Integer)
does not work (same error)
Imports System
Imports System.Collections.Generic
Imports System.Text
Public Class Vars(Of TKey, TValue)
Inherits List(Of KeyValuePair(Of TKey, TValue))
''' <summary>
''' Initializes the class and fills with Key->Value Pairs
''' </summary>
''' <remarks>
''' This does not work when adding directly from the class. When I overload
''' the Add() function, and call it with a KeyValuePair(Of String, String) in a
''' class instance it works, see below
''' </remarks>
Public Sub New()
Dim kv = New KeyValuePair(Of TKey, TValue)("This", 1)
Me.Add(kv)
End Sub
''' <summary>
''' Adds an item to the class by String, Integer
''' </summary>
''' <param name="aKey">A String containing the Key of the element to be added.</param>
''' <param name="aValue">An Integer containing the Value of the element to be added.</param>
''' <remarks>
''' This Works fine when called as in the demo shown below.
''' </remarks>
Public Overloads Sub Add(ByVal aKey As TKey, ByVal aValue As TValue)
Dim kv = New KeyValuePair(Of TKey, TValue)(aKey, aValue)
Me.Add(kv)
End Sub
''' <summary>
''' Finds a Value stored in the class based on a given Key.
''' </summary>
''' <param name="key">A String containing a Key to search for.</param>
''' <remarks>Works.</remarks>
Public Function FindByKey(ByVal key As TKey) As List(Of KeyValuePair(Of TKey, TValue))
Return Me.FindAll(Function(item As KeyValuePair(Of TKey, TValue)) (item.Key.Equals(key)))
End Function
''' <summary>
''' Finds a Key stored in the class based on a given Value.
''' </summary>
''' <param name="value">An Integer containing the Value to search for.</param>
''' <remarks>Works</remarks>
Public Function FindByValue(ByVal value As TValue) As List(Of KeyValuePair(Of TKey, TValue))
Return Me.FindAll(Function(item As KeyValuePair(Of TKey, TValue)) (item.Value.Equals(value)))
End Function
End Class
Public Class TestApp
Shared Sub Main()
Dim varTest As Vars(Of String, Integer) = New Vars(Of String, Integer)
varTest.Add("Kung", 1)
varTest.Add("Foo", 2)
For Each var In varTest
Console.WriteLine(var.Key & ":" & var.Value)
Next
'Output would be
'
' Kung:1
' Foo:2
End Sub
End Class