我们常用 Hashtable 来描述索引键/值组的集合,Hashtable 的键值是区分大小写的。
Dim oHash As New Hashtable()
Dim bIsFind As Boolean
oHash.Add("A", "ValueA")
oHash.Add("B", "ValueA")
oHash.Add("C", "ValueA")
bIsFind = oHash.Contains("a") '鍵值 "a" 不存在
bIsFind = oHash.Contains("A") '鍵值 "A" 存在
Dim bIsFind As Boolean
oHash.Add("A", "ValueA")
oHash.Add("B", "ValueA")
oHash.Add("C", "ValueA")
bIsFind = oHash.Contains("a") '鍵值 "a" 不存在
bIsFind = oHash.Contains("A") '鍵值 "A" 存在
若我们需要让 Hasktable 不区分大小写怎么处理呢?常看到的一种作法就是在 Hasktable 的加入/移除时先将键值全转为小写(或大写),而判断时也将键值同样转为小写(或大写)。
Dim oHash As New Hashtable()
Dim bIsFind As Boolean
oHash.Add("A".ToLower, "ValueA")
oHash.Add("B".ToLower, "ValueA")
oHash.Add("C".ToLower, "ValueA")
bIsFind = oHash.Contains("a".ToLower) '鍵值 "a" 存在
bIsFind = oHash.Contains("A".ToLower) '鍵值 "A" 存在
Dim bIsFind As Boolean
oHash.Add("A".ToLower, "ValueA")
oHash.Add("B".ToLower, "ValueA")
oHash.Add("C".ToLower, "ValueA")
bIsFind = oHash.Contains("a".ToLower) '鍵值 "a" 存在
bIsFind = oHash.Contains("A".ToLower) '鍵值 "A" 存在
当然上述的方式是可行为,不过略显麻烦,若键值忘了转换就加入就容易导致找不到的情形,最好的方式就是由 Hashtable 本身自行处理,让开发人员无需去理会键值大小写。
在 Hasktable 的有一多载的建构函式如下
Public Sub New ( _
equalityComparer As IEqualityComparer _
)
equalityComparer As IEqualityComparer _
)
所以我们只要撰写一个具 IEqualityComparer 接口的类别来做键值比对就可以了。
Public Class THashKeyComparer
Implements IEqualityComparer
Public Function Equals1(ByVal x As Object, ByVal y As Object) _
As Boolean Implements IEqualityComparer.Equals
Return (CStr(x).ToLower = CStr(y).ToLower)
End Function
Public Function GetHashCode1(ByVal obj As Object) _
As Integer Implements IEqualityComparer.GetHashCode
Return obj.ToString().ToLower().GetHashCode()
End Function
End Class
Implements IEqualityComparer
Public Function Equals1(ByVal x As Object, ByVal y As Object) _
As Boolean Implements IEqualityComparer.Equals
Return (CStr(x).ToLower = CStr(y).ToLower)
End Function
Public Function GetHashCode1(ByVal obj As Object) _
As Integer Implements IEqualityComparer.GetHashCode
Return obj.ToString().ToLower().GetHashCode()
End Function
End Class
当我们要使用 Hasktable 时,只要使用自定义具 IEqualityComparer 的类别来初始化 Hasktable 即可。
Dim oHash As New Hashtable(New THashKeyComparer())
Dim bIsFind As Boolean
oHash.Add("A", "ValueA")
oHash.Add("B", "ValueA")
oHash.Add("C", "ValueA")
bIsFind = oHash.Contains("a") '鍵值 "a" 存在
bIsFind = oHash.Contains("A") '鍵值 "A" 存在