c#如何定义一个含有不同类型的字典? [英] c# How can I define a dictionary that holds different types?

查看:208
本文介绍了c#如何定义一个含有不同类型的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有以下代码。你在哪里看到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},
{DescriptionText,desclangtext},
{CheckInUsed,}
};


解决方案

首次关闭: / p>

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



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



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



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



如果您知道类型的关键,那么你正在做的就是正确的方式。



其次:



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

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

  //获取第一个值
long id =((long [])defaultAmbience [CountryId])[0];


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?

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

解决方案

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:

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

or

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

这篇关于c#如何定义一个含有不同类型的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆