是否可以从C#(。Net 2.0)中的反射类型创建通用对象?
void foobar(Type t){
IList<t> newList = new List<t>(); //this doesn't work
//...
}
Type,t,直到运行时才知道。
答案 0 :(得分:119)
试试这个:
void foobar(Type t)
{
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(t);
var instance = Activator.CreateInstance(constructedListType);
}
现在该怎么办instance
?由于您不知道列表内容的类型,您可能做的最好的事情就是将instance
转换为IList
,这样您就可以拥有object
之外的其他内容。 }:
// Now you have a list - it isn't strongly typed but at least you
// can work with it and use it to some degree.
var instance = (IList)Activator.CreateInstance(constructedListType);
答案 1 :(得分:6)
static void Main(string[] args)
{
IList list = foobar(typeof(string));
list.Add("foo");
list.Add("bar");
foreach (string s in list)
Console.WriteLine(s);
Console.ReadKey();
}
private static IList foobar(Type t)
{
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(t);
var instance = Activator.CreateInstance(constructedListType);
return (IList)instance;
}
答案 2 :(得分:0)