在VB.NET中使用KeyValuePair进行具有反向查找功能的字典(C#中的示例提示需要转换)

Using KeyValuePair in VB.NET for a reverse lookup capable dictionary (example hint in C# needs converting)

我目前在VB.NET项目上,希望使用KeyValuePair来促进反向查找。

我在这里的C#中找到了一个很好的示例:http://www.dreamincode.net/forums/showtopic78080.htm,但是我在转换为VB.NET时遇到了一个小问题(手动转换和使用翻译器转换(在线carlosag)) )。 例如,我期望在Add方法中使用的语法如下:

1
2
3
    Public Sub Add(ByVal key As TKey, ByVal value As TValue)
        Me.Add(New KeyValuePair(Of Tkey(key, value))
    End Sub

而这告诉我"'System.Collections.Generic.KeyValuePair(Of TKey,TValue)的类型参数太少'"

任何帮助都肯定会有所帮助(实际上是示例的完整翻译,包括anon方法:D。


我在www.developerfusion.co.uk/tools上运行了您通过通常用于将C#转换为VB.NET的工具所引用的示例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Imports System
Imports System.Collections.Generic
Imports System.Text
Namespace ConsoleApplication1
    Class PairCollection(Of TKey, TValue)
        Inherits List(Of KeyValuePair(Of TKey, TValue))
        Public Sub Add(ByVal key As TKey, ByVal value As TValue)
            Me.Add(New KeyValuePair(Of TKey, TValue)(key, value))
        End Sub
        Public Function FindByKey(ByVal key As TKey) As List(Of KeyValuePair(Of TKey, TValue))
            Return Me.FindAll(Function(ByVal item As KeyValuePair(Of TKey, TValue)) (item.Key.Equals(key)))
        End Function
        Public Function FindByValue(ByVal value As TValue) As List(Of KeyValuePair(Of TKey, TValue))
            Return Me.FindAll(Function(ByVal item As KeyValuePair(Of TKey, TValue)) (item.Value.Equals(value)))
        End Function
    End Class
    Class Program
        Private Shared Sub Main(ByVal args As String())
            Dim menu As New PairCollection(Of String, Double)()
            menu.Add("Burger", 3.5R)
            menu.Add("Hot Dog", 2.25)
            menu.Add("Fries", 1.75)
            Console.WriteLine(menu.FindByKey("Fries")(0))
            Console.ReadLine()
        End Sub
    End Class
End Namespace

如您所见,Add()方法与您的方法略有不同。


通过使Add方法这样重载来解决:

1
2
3
Public Overloads Sub Add(ByVal key As TKey, ByVal value As TValue)
   Me.Add(New KeyValuePair(Of TKey, TValue)(key, value))
End Sub

奇怪的是,尽管MyBase.Add可以工作(通过Reflector中的反编译找到),但我却没有(尽管" this"在C#中工作)。 我想我将此归结为VB.NET的一个古怪之处了吗?

感谢Kevinw和Meta-Knight。 原始代码是错误的,但是我一直都是从List继承的。


1-正如kevinw指出的那样,您的原始代码只是错误的,应该是:

1
Me.Add(New KeyValuePair(Of TKey, TValue)(key, value))

2-上面的代码应在继承自List(Of KeyValuePair)PairCollection中插入新的KeyValuePair。 如果它不起作用,则很有可能是您的Inherits行错误。 根据错误,Add方法需要键,而不是KeyValuePair ...可能是您从Dictionary而不是List继承的?