Can I Create a Dictionary of Generic Types?

前端 未结 10 2451
误落风尘
误落风尘 2020-11-30 02:53

I\'d like to create a Dictionary object, with string Keys, holding values which are of a generic type. I imagine that it would look something like this:

Dict         


        
10条回答
  •  难免孤独
    2020-11-30 03:26

    No, but you can use object instead of generic type.

    Long answer: The current version of C# will not allow you to make entries of generic type in a dictionary. Your options are either a) create a custom class that is the same as a dictionary except allow it to accept generic types, or b) make your Dictionary take values of type object. I find option b to be the simpler approach.

    If you send lists of specific types, then when you go to process the lists you will have to test to see what kind of list it is. A better approach is to create lists of objects; this way you can enter integers, strings, or whatever data type you want and you don't necessarily have to test to see what type of object the List holds. This would (presumably) produce the effect you're looking for.

    Here is a short console program that does the trick:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace dictionary
    {
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary dic = new Dictionary();
            var lstIntList = new List();
            var lstStrings = new List();
            var lstObjects = new List();
            string s = "";
    
            lstIntList.Add(1);
            lstIntList.Add(2);
            lstIntList.Add(3);
    
            lstStrings.Add("a");
            lstStrings.Add("b");
            lstStrings.Add("c");
    
            dic.Add("Numbers", lstIntList);
            dic.Add("Letters", lstStrings);
    
            foreach (KeyValuePair kvp in dic)
            {
                Console.WriteLine("{0}", kvp.Key);
                lstObjects = ((IEnumerable)kvp.Value).Cast().ToList();
    
                foreach (var obj in lstObjects)
                   {s = obj.ToString(); Console.WriteLine(s);}
                Console.WriteLine("");
            }
    
    
            Console.WriteLine("");
            Console.WriteLine("press any key to exit");
            Console.ReadKey();
        }//end main
    }
    }
    
    
    

    提交回复
    热议问题