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

前端 未结 8 438
庸人自扰
庸人自扰 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 21:43

    You can use a Dictionary and then you can put anything you want into it. You would have to cast the results to the right type when you get them out though.

    Looking at your example though you might want to consider whether a simple class to store the data might be more what you want and allow better type safety. It depends on whether you have a limited set of things to put in the class or if you do need the potentially unlimited/unknown storage of a dictionary.

提交回复
热议问题