How do I create a Dictionary that holds different types in C#

前端 未结 8 400
庸人自扰
庸人自扰 2020-12-04 21:38

I need some sort of way to store key/value pairs where the value can be of different types.

So I like to do:

 int i = 12;
 string s = \"test\";
 doub         


        
相关标签:
8条回答
  • 2020-12-04 22:05

    Dictionary is clearly the quickest solution.

    Another way could be to store a custom class in which you could store the actual value and the information regarding its type

    0 讨论(0)
  • 2020-12-04 22:08

    Given that you don't want a strongly typed data collection then I would have thought a HashTable would be suitable for your situation. You could create an Extention method for this also, like another poster suggested for the Dictionary implementation.

    E.g.

    public static class StorageExtentions
    {
        public static T Get<T>(this Hashtable table, object key)
        {
            return (T) table[key];
        }
    }
    

    Your code would then look like:

    int i = 12;
    string s = "test";
    double x = 24.1;
    Hashtable Storage = new Hashtable();
    Storage.Add("age", i);
    Storage.Add("name", s);
    Storage.Add("bmi", x);
    int a = Storage.Get<int>("age");
    string b = Storage.Get<string>("name");
    double c = Storage.Get<double>("bmi");
    
    0 讨论(0)
提交回复
热议问题