Can I Create a Dictionary of Generic Types?

前端 未结 10 2435
误落风尘
误落风尘 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:36

    I prefer this way of putting generic types into a collection:

    interface IList
    {
      void Add (object item);
    }
    
    class MyList : List, IList
    {
      public void Add (object item)
      {
        base.Add ((T) item); // could put a type check here
      }
    }
    
    class Program
    {
      static void Main (string [] args)
      {
        SortedDictionary
          dict = new SortedDictionary ();
    
        dict [0] = new MyList ();
        dict [1] = new MyList ();
    
        dict [0].Add (42);
        dict [1].Add ("Hello"); // Fails! Type cast exception.
      }
    }
    

    But you do lose the type checks at compile time.

提交回复
热议问题