在声明处添加键/值到词典

我觉得今天非常容易。 在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) {{"",""}} 

这在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; 

这是相同的,使用From关键字:

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

但是,这需要VS2010中的语言版本10。

这是一个很酷的翻译:你也可以有一个string和string数组的通用字典。

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"}}} 

酷哈哈:)

没有构造函数可以为字典提供KeyValuePair。