【问题标题】:VB.NET: Convert Hashtable to Dictionary with generic value typeVB.NET:将 Hashtable 转换为具有通用值类型的字典
【发布时间】:2013-07-18 08:49:43
【问题描述】:

如何进行从HashtableDictionary 的转换以保持值通用?我的想法是具有如下功能:

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 中的每个对象强制转换为TCType 使用一些技巧来获得所需的类型,例如StringInt32)。如果它无法转换为目标类型,则会引发 InvalidCastException

    你为什么需要它?也许有更好的方法来实现你想要的。一般来说,你现在应该避免像ArrayListHashTable 这样的非通用集合。

    【讨论】:

    • 谢谢!实际上我需要这个才能使用遗留代码:-)
    猜你喜欢
    • 2021-08-29
    • 1970-01-01
    • 2011-09-21
    • 2010-10-16
    • 2021-02-03
    • 2015-07-28
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多