C#从反射的Type中实例化通用List

Iai*_*oat 41 c# generics reflection

是否可以从C#(.Net 2.0)中的反射类型创建通用对象?

void foobar(Type t){
    IList<t> newList = new List<t>(); //this doesn't work
    //...
}
Run Code Online (Sandbox Code Playgroud)

Type,t,直到运行时才知道.

And*_*are 123

试试这个:

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

    var instance = Activator.CreateInstance(constructedListType);
}
Run Code Online (Sandbox Code Playgroud)

现在该怎么办instance?由于您不知道列表内容的类型,因此您可以做的最好的事情就是将其转换instanceIList以下内容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);
Run Code Online (Sandbox Code Playgroud)

  • `typeof(List <>)`的+1,之前我没见过. (9认同)

csa*_*uve 7

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;
}
Run Code Online (Sandbox Code Playgroud)