有没有可能创建一个已经预先填充了值的哈希表?
也就是说,像这样:
dim myHash as new Hashtable() = {"key1", "value1", "key2", "value2" }
首先,Hashtable已经过时了。现在可以使用Dictionary(Of TKey, TValue)
。关于您的问题,使用Visual Studio 2010,您可以使用新的集合初始化语法:
Dim myDict As New Dictionary(Of Integer, String) From {{1, "One"}, {2, "Two"}}
既然您正在使用.NET 2.0,就无法使用那种语法(您仍可以并且应该使用泛型字典),因此最好的方法是使用一个方法来隐藏它:
Function CreateDictionary() As Dictionary(Of Integer, String)
Dim d As New Dictionary(Of Integer, String)
d.Add(1, "One")
d.Add(2, "Two")
Return d
End Function
Dim myDict As Dictionary(Of Integer, String) = CreateDictionary()
Function CreateHashtable() As Hashtable
Dim table = new HashTable()
table.Add("key1", "value1")
table.Add("key2", "value2")
return table
End Function
Dim myHash As Hashtable = CreateHashtable()
Dim myHash As New Hashtable() From {
{"key1", "value1"}, {"key2", "value2"}
}