首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在声明时将键/值添加到字典

在声明时将键/值添加到字典
EN

Stack Overflow用户
提问于 2010-09-23 01:24:27
回答 4查看 65K关注 0票数 77

我觉得今天很简单。在C#中,its:

代码语言:javascript
运行
复制
Dictionary<String, String> dict = new Dictionary<string, string>() { { "", "" } };

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

代码语言:javascript
运行
复制
Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) (("",""))

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

我也尝试过:

代码语言:javascript
运行
复制
Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) ({"",""})

还有..。

代码语言:javascript
运行
复制
Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {("","")}

还有..。

代码语言:javascript
运行
复制
Public dict As Dictionary(Of String, String) = New Dictionary(Of String, String) {{"",""}}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-09-23 01:30:08

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

代码语言:javascript
运行
复制
Dim dict = New Dictionary(Of Integer, String) From {{ 1, "Test1" }, { 2, "Test1" }}

不幸的是,IIRCVS2008使用的是不支持这种语法的VB.NET 9编译器。

对于那些可能感兴趣的人,这里是幕后发生的事情(C#):

代码语言:javascript
运行
复制
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;
票数 122
EN

Stack Overflow用户

发布于 2010-09-23 01:33:09

基本相同,使用From关键字:

代码语言:javascript
运行
复制
    Dim d As New Dictionary(Of String, String) From {{"", ""}}

但是,这需要该语言的版本10,可在VS2010中使用。

票数 15
EN

Stack Overflow用户

发布于 2012-09-19 11:06:16

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

C#

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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"}}}

酷哈:)

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3771922

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档