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

前端 未结 3 1479
旧时难觅i
旧时难觅i 2021-02-20 14:54

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

相关标签:
3条回答
  • 2021-02-20 15:11

    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. In case of this long array this would be:

    ((long[])defaultAmbience["CountryId"])[0]
    
    0 讨论(0)
  • 2021-02-20 15:20

    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];
    
    0 讨论(0)
  • 2021-02-20 15:27

    You'd need to provide the cast where you call it.

    ((long[])defaultAmbience["countryID"])[0];
    
    0 讨论(0)
提交回复
热议问题