【问题标题】:Add keys/values to Dictionary at declaration在声明时将键/值添加到字典
【发布时间】:2011-04-15 21:00:10
【问题描述】:

我想今天很容易。在 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) {{"",""}}

【问题讨论】:

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


    【解决方案1】:

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

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

    酷哈哈:)

    【讨论】:

      【解决方案2】:

      大同小异,使用From关键字:

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

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

      【讨论】:

      • 这更好,因为 CLR 可以比接受的答案更好地优化它。
      【解决方案3】:

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

      【讨论】:

      • 很好!我想知道它是如何表现的,它是先构建二维数组,然后再复制到字典中吗?
      • 邓恩。所以你是说因为我使用的是VS2008我不能这样做?太臭了。
      • 是的,有点臭 :-) 是时候升级了。
      • 有没有办法将二维数组转换为字典?如果是这样,我只会这样做。我的目标是我有 ViewModes 并且每种模式都有一个单独的查询。我想遍历字典,将键添加到视图模式组合框,值将是查询。或类似的东西。也许我必须使用二维数组。
      • 我最终只是将其设为属性并将它们添加到其中。不知道为什么我之前没有想到。
      【解决方案4】:

      没有将 KeyValuePair 用作字典的构造函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 2017-11-15
        • 1970-01-01
        • 2016-02-09
        • 2016-05-15
        • 2018-10-19
        相关资源
        最近更新 更多