【问题标题】:VB.NET: Convert Hashtable to Dictionary with generic value typeVB.NET:将 Hashtable 转换为具有通用值类型的字典
【发布时间】:2013-07-18 08:49:43
【问题描述】:
如何进行从Hashtable 到Dictionary 的转换以保持值通用?我的想法是具有如下功能:
Public Function Hashtable2Dictionary(Of T)(ht As Hashtable) As Dictionary(Of String, T)
' do conversion here
End Function
【问题讨论】:
标签:
vb.net
generics
dictionary
hashtable
【解决方案1】:
也许:
Public Function Hashtable2Dictionary(Of T)(ht As Hashtable) As Dictionary(Of String, T)
If ht Is Nothing Then Return Nothing
Dim dict = New Dictionary(Of String, T)(ht.Count)
For Each kv As DictionaryEntry In ht
dict.Add(kv.Key.ToString(), CType(ht(kv.Value), T))
Next
Return dict
End Function
您不能将Hashtable 直接转换为Dictionary。您可以尝试将HashTable 中的每个对象强制转换为T(CType 使用一些技巧来获得所需的类型,例如String 到Int32)。如果它无法转换为目标类型,则会引发 InvalidCastException。
你为什么需要它?也许有更好的方法来实现你想要的。一般来说,你现在应该避免像ArrayList 或HashTable 这样的非通用集合。