Creating a Generic type instance with a variabl

2019-01-01 06:55发布

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>();

3条回答
柔情千种
2楼-- · 2019-01-01 07:25

Try this:

var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);
查看更多
长期被迫恋爱
3楼-- · 2019-01-01 07:39

Yes, there is:

var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);
查看更多
人间绝色
4楼-- · 2019-01-01 07:45

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>());
}
查看更多
登录 后发表回答