Is het mogelijk om een generiek object te maken van een gereflecteerd type in C# (.Net 2.0)?
void foobar(Type t){
IList<t> newList = new List<t>(); //this doesn't work
//...
}
Het Type, t, is niet bekend tot runtime.
Antwoord 1, autoriteit 100%
Probeer dit:
void foobar(Type t)
{
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(t);
var instance = Activator.CreateInstance(constructedListType);
}
Wat nu te doen met instance
? Aangezien u het type inhoud van uw lijst niet kent, kunt u waarschijnlijk het beste instance
casten als een IList
zodat u iets anders kunt hebben dan gewoon een 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);
Antwoord 2, autoriteit 6%
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;
}
Antwoord 3
U kunt MakeGenericType
gebruiken voor dergelijke bewerkingen.