简体   繁体   English

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

[英]c# How can I define a dictionary that holds different types?

If have the following code. 如果有以下代码。 Where you see the XXX I would like to put in an array of type long[]. 你在哪里看到XXX我想放入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? 我只是使用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", "" }
};

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 Generics最适合。 .NET also provides an entire set of collections for use when you want to store a "mixed bag" of objects of different types. .NET还提供了一整套集合,供您在需要存储不同类型对象的“混合包”时使用。

In this case, the equivalent of the Dictionary would be the HashTable . 在这种情况下,Dictionary的等价物将是HashTable

Check out the System.Collections (rather than System.Collections.Generic) namespace to see the rest of the options you have. 查看System.Collections (而不是System.Collections.Generic)命名空间,以查看您拥有的其他选项。

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];

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

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

In this case C# doesn't really know what type you expect to get, so you have to cast to the correct type after you take it from the dictionary and before you use it. 在这种情况下,C#并不真正知道您希望获得什么类型,因此在从字典中获取之后以及使用它之前,必须转换为正确的类型。 In case of this long array this would be: 在这个长数组的情况下,这将是:

((long[])defaultAmbience["CountryId"])[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM