Creating a Generic<T> type instance with a variable containing the Type

柔情痞子 提交于 2019-11-26 00:37:30

问题


Is it possible to achieve the following code? I know it doesn\'t work, but I\'m wondering if there is a workaround?

Type k = typeof(double);
List<k> lst = new List<k>();

回答1:


Yes, there is:

var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);



回答2:


A cleaner way might be to use a generic method. Do something like this:

static void AddType<T>()
    where T : DataObject
{
    Indexes.Add(typeof(T), new Dictionary<int, T>());
}



回答3:


Try this:

var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);


来源:https://stackoverflow.com/questions/2078914/creating-a-generict-type-instance-with-a-variable-containing-the-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!