vb.net 在声明时将键/值添加到字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3771922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add keys/values to Dictionary at declaration
提问by XstreamINsanity
Very easy today, I think. In C#, its:
今天很轻松,我想。在 C# 中,它的:
Dictionary<String, String> dict = new Dictionary<string, string>() { { "", "" } };
But in vb, the following doesn't work.
但在 vb 中,以下不起作用。
Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) (("",""))
I'm pretty sure there's a way to add them at declaration, but I'm not sure how. And yes, I want to add them at declaration, not any other time. :) So hopefully it's possible. Thanks everyone.
我很确定有一种方法可以在声明时添加它们,但我不确定如何。是的,我想在声明时添加它们,而不是任何其他时间。:) 所以希望这是可能的。谢谢大家。
I've also tried:
我也试过:
Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) ({"",""})
And...
和...
Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {("","")}
And...
和...
Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {{"",""}}
回答by Darin Dimitrov
This is possible in VB.NET 10:
这在 VB.NET 10 中是可能的:
Dim dict = New Dictionary(Of Integer, String) From {{ 1, "Test1" }, { 2, "Test1" }}
Unfortunately IIRC VS 2008 uses VB.NET 9 compiler which doesn't support this syntax.
不幸的是 IIRC VS 2008 使用不支持这种语法的 VB.NET 9 编译器。
And for those that might be interested here's what happens behind the scenes (C#):
对于那些可能感兴趣的人,这里是幕后发生的事情 (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;
回答by Hans Passant
It is much the same, use the From keyword:
大致相同,使用 From 关键字:
Dim d As New Dictionary(Of String, String) From {{"", ""}}
However, this requires version 10 of the language, available in VS2010.
但是,这需要 VS2010 中可用的语言版本 10。
回答by Mike
Here's a cool translation: You can also have a Generic Dictionary of strings and string array.
这是一个很酷的翻译:您还可以拥有一个字符串和字符串数组的通用字典。
C#:
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:
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"}}}
Cool haa :)
酷哈哈:)
回答by vulkanino
There's no constructor to take a KeyValuePair for a dictionary.
没有构造函数可以为字典采用 KeyValuePair。