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

前端 未结 8 434
庸人自扰
庸人自扰 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: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(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("age");
    string b = Storage.Get("name");
    double c = Storage.Get("bmi");
    

提交回复
热议问题