0

问题:我使用在这里找到的双向字典类: 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
4

1 回答 1

1

您正在尝试编写一个通用的双字典,它可以具有任何类型的键/值对组合。使用 比较两个整数是什么意思StringComparer?我建议您将构造函数更改为采用两个 IEqualityComparers,一个 forTKey和一个 for TValue。然后,您可以通过传入两个适当的值来创建BiDictionaryOneToOne(Of String, String)不区分大小写的。IEqualityComparer(Of String)

于 2011-02-25T10:30:09.237 回答