代码之家  ›  专栏  ›  技术社区  ›  Martin

C我如何定义一个包含不同类型的字典?

  •  10
  • Martin  · 技术社区  · 14 年前

    如果有以下代码。在这里,您可以看到我要放入long[]类型的数组。

    我如何才能做到这一点,以及如何从字典中获取值?我是否只使用defaultAmbience[“countryID”[0]获取第一个元素?

    public static Dictionary<string, object> defaultAmbience = new Dictionary<string, object>
    {
        { "UserId", "99999" },
        { "CountryId", XXX },
        { "NameDefaultText", "nametext" },
        { "NameCulture", "it-IT" },
        { "NameText", "namelangtext" },
        { "DescriptionDefaultText", "desctext" },
        { "DescriptionCulture", "it-IT" },
        { "DescriptionText", "desclangtext" },
        { "CheckInUsed", "" }
    };
    
    3 回复  |  直到 8 年前
        1
  •  8
  •   Ben Collins    12 年前

    第一关:

    如果您不知道值或键的类型 ,那么不要使用通用字典。

    .NET泛型最适合提前知道类型的情况。.NET还提供了一整套集合,用于存储不同类型的对象的“混合包”。

    在这种情况下,相当于字典的是 HashTable .

    退房 System.Collections (而不是System.Collections.Generic)命名空间以查看其余选项。

    如果你知道钥匙的类型,那么你所做的就是正确的方法。

    其次:

    当您检索值时…您需要将对象强制转换回其原始类型:

    long[] countryIds = (long[]) defaultAmbience["CountryId"];
    

    // To get the first value
    long id = ((long[])defaultAmbience["CountryId"])[0];
    
        2
  •  2
  •   Mark H    14 年前

    你需要提供你所称的演员阵容。

    ((long[])defaultAmbience["countryID"])[0];
    
        3
  •  1
  •   Grzenio    14 年前

    在这种情况下,c不知道您希望得到什么类型,所以您必须在从字典中取出并使用它之前强制转换到正确的类型。在这种长数组的情况下,这将是:

    ((long[])defaultAmbience["CountryId"])[0]