开发者

Instantiate a generic list from object

开发者 https://www.devze.com 2023-03-23 02:30 出处:网络
I have the following code public void MyMethod(object myClass) { if(myClass.GetType().IsSubclassOf(typeof(MyBaseClass)))

I have the following code

    public void MyMethod(object myClass)
    {
       if(myClass.GetType().IsSubclassOf(typeof(MyBaseClass)))
       {
          // Instantiate a generic list here....
          // Assume that myClass is type Class1, e.g. List<Class1> abc = new List<Class1>();
       }
    }

Within the if开发者_StackOverflow社区 statement I want to create a List of the type of myClass. Is this possible? I am assuming it is through reflection but I can't see how to do it.


Type genericListType = typeof(List<>).MakeGenericType(new Type[] { myClass.GetType() });
object list = Activator.CreateInstance(genericListType);
0

精彩评论

暂无评论...
验证码 换一张
取 消