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)
首先:
如果您不知道值的类型或键,则不要使用通用字典.
当您提前了解类型时,.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)