Ist es möglich, ein generisches Objekt aus einem reflektierten Typ in C # (.Net 2.0) zu erstellen?
void foobar(Type t){
IList<t> newList = new List<t>(); //this doesn't work
//...
}
Der Typ t ist erst zur Laufzeit bekannt.
Versuche dies:
void foobar(Type t)
{
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(t);
var instance = Activator.CreateInstance(constructedListType);
}
Was macht man nun mit instance
? Da Sie den Inhalt Ihrer Liste nicht kennen, könnten Sie instance
wahrscheinlich als IList
umsetzen, damit Sie etwas anderes als nur object
haben können:
// 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;
}