【问题标题】:What's the easiest way to get Dictionary functionality in VB.NET?在 VB.NET 中获取字典功能的最简单方法是什么?
【发布时间】:2011-01-23 09:16:50
【问题描述】:

我想静态定义一个映射的字符串数组,例如:

var dict = {cat:50, bat:10, rat:30};

并在其中查找值,例如:

MessageBox.Show( dict["cat"] )

【问题讨论】:

  • 您使用的是 C# 还是 VB.NET?您的代码示例显示 C#,但您的标签显示 VB.NET。
  • 这实际上是 JavaScript :) 但我想在 VB.NET 中做类似的事情。

标签: vb.net arrays dictionary string


【解决方案1】:
Dim dict As New Dictionary(Of String, Integer)()

With dict 
    .Add("Cat", 50)
    .Add("Bat", 10)
    .Add("Rat", 30)
End With

【讨论】:

  • As New Dictionary?还是自从我上次使用以来 VB 发生了变化?
  • 这是唯一的方法吗? VB 没有对键控数组的内置支持吗?
  • @dotjoe,Kyle,smoore:这只是一种简短的做法: Dim dict As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)() 这是一个速记版本of: Dim dict As Dictionary(Of String, Integer) dict = New Dictionary(Of String, Integer)() 由于这种情况是“特殊”情况,因此可以使用最短版本:为变量分配一个值在 decleration 后立即重新创建分配的值,并且变量的类型与值的类型相同。
  • cool SO 现在可以识别您最近回复中的@username 评论回复。在 Hanin 大声笑...我认为您错过了答案中缺少 New 的部分。
  • @dotjoe,我确实做到了!以为你们是 New 关键字的新手 :-)
【解决方案2】:

在 .NET 4.0 中:

Dim d As Dictionary(Of String, Integer) From
    {{"cat", 50}, {"bat", 10}, {"rat",30 }} 

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-09-13
  • 2011-04-24
  • 2011-02-17
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
相关资源
最近更新 更多