Collection of generic types

前端 未结 9 804
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 21:06

If I have a generic class:

public class MyClass 
{
  public T Value;
}

I want to instantiate several items such as...



        
9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 21:10

    Have your generic class inherit from a non-generic base, or implement a non-generic interface. Then you can have a collection of this type and cast within whatever code you use to access the collection's contents.

    Here's an example.

    public abstract class MyClass
    {
        public abstract Type Type { get; }
    }
    
    public class MyClass : MyClass
    {
        public override Type Type
        {
            get { return typeof(T); }
        }
    
        public T Value { get; set; }
    }
    
    // VERY basic illustration of how you might construct a collection
    // of MyClass objects.
    public class MyClassCollection
    {
        private Dictionary _dictionary;
    
        public MyClassCollection()
        {
            _dictionary = new Dictionary();
        }
    
        public void Put(MyClass item)
        {
            _dictionary[typeof(T)] = item;
        }
    
        public MyClass Get()
        {
            return _dictionary[typeof(T)] as MyClass;
        }
    }
    

提交回复
热议问题