How do I create a dynamic type List

前端 未结 4 1105
野趣味
野趣味 2020-12-09 11:47

I don\'t want my List to be of fixed type. Rather I want the creation of List to be dependent on the type of variable. This code doesn\'t work:

using System;         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 12:47

    string something = "Apple";
    Type type = something.GetType();
    Type listType = typeof(List<>).MakeGenericType(new [] { type } );
    IList list = (IList)Activator.CreateInstance(listType);
    

    This is how you create a list of statically unknown type. But notice that you are unable to mention the runtime type of the list statically. You have to use a non-generic type or even object.

    Without knowing more about what you want to accomplish this is the best you can do.

提交回复
热议问题