2010-09-22 59 views
50

今天很簡單,我想。在C#中,它的:在聲明中添加鍵/值到詞典

Dictionary<String, String> dict = new Dictionary<string, string>() { { "", "" } }; 

但是在vb中,以下不起作用。

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) (("","")) 

我很確定有一種方法可以在聲明中添加它們,但我不知道如何。是的,我想在聲明中添加它們,而不是其他時間。 :)所以希望這是可能的。感謝大家。

我也試過:

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) ({"",""}) 

而且......

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {("","")} 

而且......

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {{"",""}} 

回答

81

這是可能在VB.NET 10:

Dim dict = New Dictionary(Of Integer, String) From {{ 1, "Test1" }, { 2, "Test1" }} 

不幸的是IIRC VS 2008使用VB.NET 9編譯器不支持此語法。

而對於那些可能會感興趣,這裏的幕後發生了什麼(C#):

Dictionary<int, string> VB$t_ref$S0 = new Dictionary<int, string>(); 
VB$t_ref$S0.Add(1, "Test1"); 
VB$t_ref$S0.Add(2, "Test1"); 
Dictionary<int, string> dict = VB$t_ref$S0; 
+0

罰款!我不知道這是如何表現的,它是否先構建二維數組,然後將其複製到字典中? – vulkanino 2010-09-22 17:34:11

+0

Dern。所以你說,因爲我使用VS2008,我無法做到這一點?那臭味。 – XstreamINsanity 2010-09-22 17:43:10

+1

Yeap,有點臭:-)升級的時間。 – 2010-09-22 17:44:45

0

有沒有構造採取KeyValuePair的字典。

8

它是大同小異,使用From關鍵字:

Dim d As New Dictionary(Of String, String) From {{"", ""}} 

然而,這需要該語言的版本10,可在VS2010中獲得。

7

下面是一個很酷的翻譯:你也可以有一個字符串和字符串數組的泛型字典。

C#

private static readonly Dictionary<string, string[]> dics = new Dictionary<string, string[]> 
     { 
      {"sizes", new string[] {"small", "medium", "large"}}, 
      {"colors", new string[] {"black", "red", "brown"}}, 
      {"shapes", new string[] {"circle", "square"}} 
     }; 

VB

Private Shared ReadOnly dics As New Dictionary(Of String, String()) From { _ 
{"sizes", New String() {"small", "medium", "large"}}, _ 
{"colors", New String() {"black", "red", "brown"}}, _ 
{"shapes", New String() {"circle", "square"}}} 

酷HAA :)