C#我如何定义持有不同类型的字典? [英] c# How can I define a dictionary that holds different types?
问题描述
如果有下面的代码。你在哪里看到我XXX想放长型[]数组。
我怎样才能做到这一点,我怎么会从字典中获取价值? ?难道我只是用defaultAmbience [CountryId] [0]来获得的第一个元素
公共静态字典<字符串对象> ; defaultAmbience =新词典<字符串对象>
{
{用户ID,99999},
{CountryIdXXX}
{NameDefaultText,nametext},
{ NameCulture,IT-IT},
{NameText,namelangtext},
{DescriptionDefaultText,desctext},
{DescriptionCulture,它-IT},
{descriptiontext描述,desclangtext},
{CheckInUsed,}
};
第一关:
的如果你不知道该值的类型或键的,那么就不要使用通用词典。
.NET泛型是最适合当你知道时间提前的类型。 .NET还提供整套收藏,因为当你要存储不同类型的对象的鱼龙混杂使用的。
在这种情况下,在相当于字典是href=\"http://msdn.microsoft.com/en-us/library/system.collections.hashtable.add.aspx\" rel=\"nofollow\">哈希表的 查看系统。集合(而不是System.Collections.Generic)命名空间,看看你有其余的选项。 的如果你知道的类型键,然后你在做什么是正确的做法的 第二: 在retreive价值......你将需要转换的对象返回到原来的类型: 或 If have the following code. Where you see the XXX I would like to put in an array of type long[]. How can I do this and how would I fetch values from the dictionary? Do I just use defaultAmbience["CountryId"][0] to get the first element?
First Off: If you don't know the type of the value OR the key, then don't use the Generic Dictionary. .NET Generics are best suited for when you know the types ahead of time. .NET also provides an entire set of collections for use when you want to store a "mixed bag" of objects of different types. In this case, the equivalent of the Dictionary would be the HashTable. Check out the System.Collections (rather than System.Collections.Generic) namespace to see the rest of the options you have. If you know the type of the key, then what you're doing is the right way. Secondly: When you retreive the value...you're going to need to cast the object back out to its original type: or
这篇关于C#我如何定义持有不同类型的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
长[] = countryIds(长[])defaultAmbience [CountryId];
//为了得到第一个价值
长ID =((长[])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", "" }
};
long[] countryIds = (long[]) defaultAmbience["CountryId"];
// To get the first value
long id = ((long[])defaultAmbience["CountryId"])[0];