问题:我使用在这里找到的双向字典类: Bidirectional 1 to 1 Dictionary in C#
问题是,我需要这个 - 不区分大小写(StringComparer.OrdinalIgnoreCase)
我想扩展它以涵盖 IEqualityComparer 构造函数。我已经将它转换为 VB(就像一个魅力),但我在实现比较器“传输”时遇到了麻烦。
问题是,在我的参数中:
ByVal x As System.Collections.Generic.IEqualityComparer(Of TKey)
但是字典 secondToFirst 是 TValue 类型,TKey,这会杀死我的 IEqualityComparer,它需要是 TValue 类型而不是 TKey ...
我如何对这个比较器进行类型转换?
如果某个地方有另一个 BiDictionaryOneToOne 类,不区分大小写,那也没关系(只要该库在大小/内存消耗和 .NET 2.0 方面不是巨大的)
Public Class BiDictionaryOneToOne(Of TKey, TValue)
Public Sub New(ByVal x As System.Collections.Generic.IEqualityComparer(Of TKey))
Dim y As System.Collections.Generic.IEqualityComparer(Of TValue) = StringComparer.OrdinalIgnoreCase
firstToSecond = New Dictionary(Of TKey, TValue)(x)
secondToFirst = New Dictionary(Of TValue, TKey)(y)
End Sub
编辑:
好的,当然只有当 TKey 和 TValue 是字符串类型时才有可能,正如 John 指出的那样,但如果它们相同,那么使用 try/catch 仍然是可能的:
Public Sub New(ByVal cmpFirstDirection As System.Collections.Generic.IEqualityComparer(Of TKey))
Try
Dim cmpOppositeDirection As System.Collections.Generic.IEqualityComparer(Of TValue) = CType(cmpFirstDirection, System.Collections.Generic.IEqualityComparer(Of TValue))
firstToSecond = New Dictionary(Of TKey, TValue)(cmpFirstDirection)
secondToFirst = New Dictionary(Of TValue, TKey)(cmpOppositeDirection)
Catch ex As Exception
firstToSecond = New Dictionary(Of TKey, TValue)(cmpFirstDirection)
secondToFirst = New Dictionary(Of TValue, TKey)
End Try
End Sub
Public Sub New(ByVal cmpFirstDirection As System.Collections.Generic.IEqualityComparer(Of TKey), ByVal cmpOppositeDirection As System.Collections.Generic.IEqualityComparer(Of TValue))
firstToSecond = New Dictionary(Of TKey, TValue)(cmpFirstDirection)
secondToFirst = New Dictionary(Of TValue, TKey)(cmpOppositeDirection)
End Sub