在声明时将键/值添加到Dictionary

时间:2010-09-22 17:24:27

标签: vb.net visual-studio-2008 dictionary declaration

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

4 个答案:

答案 0 :(得分:98)

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

答案 1 :(得分:10)

大致相同,请使用From关键字:

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

但是,这需要在VS2010中提供该语言的第10版。

答案 2 :(得分:9)

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

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

酷哈哈:)

答案 3 :(得分:1)

没有构造函数可以为字典获取KeyValuePair。