c#如何定义包含不同类型的字典?

Mar*_*tin 10 c# dictionary types

如果有以下代码.你在哪里看到XXX我想放入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", "" }
};
Run Code Online (Sandbox Code Playgroud)

Jus*_*ner 8

首先:

如果您不知道值的类型或键,则不要使用通用字典.

当您提前了解类型时,.NET Generics最适合..NET还提供了一整套集合,供您在存储不同类型对象的"混合包"时使用.

在这种情况下,Dictionary的等价物将是HashTable.

查看System.Collections(而不是System.Collections.Generic)命名空间,以查看您拥有的其他选项.

如果您知道密钥的类型,那么您正在做的是正确的方法.

其次:

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

long[] countryIds = (long[]) defaultAmbience["CountryId"];
Run Code Online (Sandbox Code Playgroud)

要么

// To get the first value
long id = ((long[])defaultAmbience["CountryId"])[0];
Run Code Online (Sandbox Code Playgroud)

  • 使用非泛型类型实际上并没有帮助 - 他仍然需要进行演员等.他确实知道键将成为字符串,所以他实际上从使用泛型版本中获得了一些好处. (6认同)
  • `Dictionary <string,object>`有什么问题?对我来说,显示存储混合物品的意图更加清晰.此外,它阻止你尝试使用非字符串键(见http://stackoverflow.com/questions/1433713/which-collection-class-to-use-hashtable-or-dictionary/1433736#1433736) (3认同)