web-dev-qa-db-fra.com

C # instancie la liste générique du type reflété

Est-il possible de créer un objet générique à partir d'un type reflété en C # (.Net 2.0)?

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

Le type, t, n'est pas connu avant l'exécution.

39
Iain Sproat

Essaye ça:

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

    var instance = Activator.CreateInstance(constructedListType);
}

Maintenant que faire avec instance? Puisque vous ne connaissez pas le type du contenu de votre liste, la meilleure chose à faire serait probablement de transtyper instance en tant que IList afin que vous puissiez avoir autre chose que 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);
117
Andrew Hare
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;
}
6
csauve

Vous pouvez utiliser MakeGenericType pour de telles opérations.

Pour la documentation, voir ici et ici .

0
Ilya Kogan