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

Xst*_*ity 65 vb.net dictionary declaration visual-studio-2008

我想今天非常容易.在C#中,它:

Dictionary<String, String> dict = new Dictionary<string, string>() { { "", "" } };
Run Code Online (Sandbox Code Playgroud)

但是在vb中,以下内容不起作用.

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) (("",""))
Run Code Online (Sandbox Code Playgroud)

我很确定有一种方法可以在声明中添加它们,但我不确定如何.是的,我想在声明中添加它们,而不是任何其他时间.:)所以希望它是可能的.感谢大家.

我也尝试过:

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) ({"",""})
Run Code Online (Sandbox Code Playgroud)

和...

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {("","")}
Run Code Online (Sandbox Code Playgroud)

和...

Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {{"",""}}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 106

这在VB.NET 10中是可能的:

Dim dict = New Dictionary(Of Integer, String) From {{ 1, "Test1" }, { 2, "Test1" }}
Run Code Online (Sandbox Code Playgroud)

不幸的是,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;
Run Code Online (Sandbox Code Playgroud)

  • 是的,有点臭:-)升级时间。 (2认同)

Han*_*ant 12

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

    Dim d As New Dictionary(Of String, String) From {{"", ""}}
Run Code Online (Sandbox Code Playgroud)

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


小智 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"}}
        };
Run Code Online (Sandbox Code Playgroud)

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"}}}
Run Code Online (Sandbox Code Playgroud)

酷哈哈:)