C#从反射类型实例化泛型列表

C#从反射类型实例化泛型列表,c#,reflection,generics,C#,Reflection,Generics,是否可以从C#(.NET2.0)中的反射类型创建泛型对象 void foobar(t型){ IList newList=newList();//这不起作用 //... } 直到运行时才知道类型t。请尝试以下操作: void foobar(Type t) { var listType = typeof(List<>); var constructedListType = listType.MakeGenericType(t); var instance =

是否可以从C#(.NET2.0)中的反射类型创建泛型对象

void foobar(t型){
IList newList=newList();//这不起作用
//...
}
直到运行时才知道类型t。

请尝试以下操作:

void foobar(Type t)
{
    var listType = typeof(List<>);
    var constructedListType = listType.MakeGenericType(t);

    var instance = Activator.CreateInstance(constructedListType);
}

您可以使用
MakeGenericType
进行此类操作

有关文档,请参阅和。

static void Main(字符串[]args)
{
IList list=foobar(typeof(string));
列表。添加(“foo”);
列表。添加(“酒吧”);
foreach(列表中的字符串s)
控制台。写入线(s);
Console.ReadKey();
}
专用静态IList foobar(t型)
{
var listType=类型(列表);
var constructedListType=listType.MakeGenericType(t);
var instance=Activator.CreateInstance(constructedListType);
返回(IList)实例;
}

对于编译时不知道其类型的列表,您希望如何处理?您是否能够将其作为通用函数编写,如
void foobar(){IList newList=newList();}
我感觉这可能是一种代码味道,由于以一种糟糕的方式解决了一个更大的问题。我发布了一个关于手头更大问题的单独问题:+1 for
typeof(List)
,我以前从未见过这种情况。
var
是否存在于.Net framework 2.0中@sprocketonline:
var
是一个C#3特性,因此如果您使用C#2,您需要显式声明变量。谢谢,这个答案对我帮助很大。正是我所需要的(我正在为EF构建表达式)+1,以记住好的非通用支持接口:)
void foobar(Type t)
{
    var listType = typeof(List<>);
    var constructedListType = listType.MakeGenericType(t);

    var instance = Activator.CreateInstance(constructedListType);
}
// 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);
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;
}