Collection of generic types

前端 未结 9 825
爱一瞬间的悲伤
爱一瞬间的悲伤 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:13

    IList

    There is no way to define a generic collection that can accept any flavor of your generic class... ie IList. Generic classes are only a short cut for the developer to save on writing a bunch of repetitive code but at compile time each flavor of the generic class is translated into a concrete. i.e. if you have MyClass, MyClass, MyClass then the compiler will generate 3 seperate and distinct classes. The only way to do what you want is to have an interface for your generic.

    public interface IMyGeneric {
        Type MyType { get; set;}    
    }
    
    class MyGeneric : IMyGeneric {
    
        public MyGeneric() {
            MyType = typeof(T);
        }
    
        public Type MyType {
            get; set;
        }
    }
    

    and then you can say

    IList list = new List();
    list.add(new MyGeneric());
    list.add(new MyGeneric());
    

提交回复
热议问题