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

前端 未结 8 435
庸人自扰
庸人自扰 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:03

    You could declare a Dictionary containing just the type object and then cast your results; .e.g.

    Dictionary storage = new Dictionary();
    
    storage.Add("age", 12);
    storage.Add("name", "test");
    storage.Add("bmi", 24.1);
    
    int a = (int)storage["age"];
    string b = (string)storage["name"];
    double c = (double)storage["bmi"];
    

    However, this isn't that elegant. If you know you are always going to be storing age, name, bmi I would create an object to encapsulate those and store that instead. E.g.

    public class PersonInfo
    {
        public int Age { get; set; }
        public string Name { get; set; }
        public double Bmi { get; set; }
    }
    

    And then use that insead of the Dictionary... e.g.

    PersonInfo person1 = new PersonInfo { Name = "test", Age = 32, Bmi = 25.01 };
    
    int age = person1.Age;
    

    etc.

提交回复
热议问题