С# экземпляр обобщенного списка из отраженного типа
Можно ли создать общий объект из отраженного типа в С# (.Net 2.0)?
void foobar(Type t){
IList<t> newList = new List<t>(); //this doesn't work
//...
}
Тип t не известен до времени выполнения.
Ответ 1
Попробуйте следующее:
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);
Ответ 2
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;
}
Ответ 3
Вы можете использовать MakeGenericType для таких операций.