値を一般的なものに変換するHashtable
にはどうすればよいですか? Dictionary
私の考えは、次のような機能を持つことです。
Public Function Hashtable2Dictionary(Of T)(ht As Hashtable) As Dictionary(Of String, T)
' do conversion here
End Function
値を一般的なものに変換するHashtable
にはどうすればよいですか? Dictionary
私の考えは、次のような機能を持つことです。
Public Function Hashtable2Dictionary(Of T)(ht As Hashtable) As Dictionary(Of String, T)
' do conversion here
End Function
多分:
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
aを aDictionary
に直接キャストすることはできません。to 内のすべてのオブジェクトをキャストすることを試みることができます( HashTable
toなど、目的の型を取得するためにいくつかのトリックを使用します) 。ターゲットの型にキャストできない場合は、 anが発生します。T
CType
String
Int32
InvalidCastException
なぜあなたはそれが必要なのですか?たぶん、あなたが望むものを達成するためのより良い方法があります。ArrayList
一般に、やHashTable
最近のような非ジェネリック コレクションは避けるべきです。