C# 使用包含 Type 的变量创建 Generic<T> 类型实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2078914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:19:35  来源:igfitidea点击:

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

c#genericstypesinstance

提问by Chris

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

采纳答案by David M

Yes, there is:

就在这里:

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

回答by Bryan Legend

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

回答by test

Try this:

尝试这个:

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