使用VB.NET中的值创建哈希表

chr*_*ris 5 vb.net hashtable .net-2.0

是否可以使用值创建"预先填充"的哈希表?

就是这样的:

dim myHash as new Hashtable() = {"key1", "value1", "key2", "value2" }
Run Code Online (Sandbox Code Playgroud)

Joe*_*orn 7

首先,Hashtable现在已经老了.请Dictionary(Of TKey, TValue)改用.至于您的问题,使用Visual Studio 2010,您可以使用新的集合初始化程序语法:

Dim myDict As New Dictionary(Of Integer, String) From {{1, "One"}, {2, "Two"}}
Run Code Online (Sandbox Code Playgroud)

由于您使用的是.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()
Run Code Online (Sandbox Code Playgroud)