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

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

    maybe it is an old question, but I am addressing the guys who come here to find the answer

    if the value is not a fixed type one of the choices is using Hashtable please look at the implementation of both Dictionary and Hashtable

        public class Dictionary : ICollection>, IEnumerable>, IEnumerable, IDictionary, IReadOnlyCollection>, IReadOnlyDictionary, ICollection, IDictionary, IDeserializationCallback, ISerializable
         {
                  ... 
         }

    public class Hashtable : ICollection, IEnumerable, IDictionary, ISerializable, IDeserializationCallback, ICloneable
      {
       ...
      }

    as it gets more clear from above code snippets, both implement literally the same interfaces but in Hashtable there is no type on both key & value since both of them considered to be intrinsically objects, for example you can see from add method in Hashtable:

    public virtual void Add(object key, object value);

    so for the cases of not having fixed keys and/or values, I recommend using Hashtable, therefore you don't need to add extra extension methods or override default behavior of a dictionary any more.

提交回复
热议问题