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

时间:2010-06-21 15:55:50

标签: 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", "" }
};

3 个答案:

答案 0 :(得分:8)

首先关闭:

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

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

在这种情况下,词典的等​​价物将是HashTable

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

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

<强>其次:

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

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

// To get the first value
long id = ((long[])defaultAmbience["CountryId"])[0];

答案 1 :(得分:2)

您需要在您调用它的地方提供演员表。

((long[])defaultAmbience["countryID"])[0];

答案 2 :(得分:1)

在这种情况下,C#并不真正知道您希望获得什么类型,因此您必须在从字典中获取并在使用之前强制转换为正确的类型。在这个长数组的情况下,这将是:

((long[])defaultAmbience["CountryId"])[0]
相关问题