Ich arbeite an einem Reflexionsprojekt, und jetzt stecke ich fest. Wenn ich ein Objekt von "myclass" habe, das eine Liste enthalten kann weiß jemand, wie man den Typ wie im folgenden Code erhält, wenn die Eigenschaft myclass.SomList leer ist?C# generische Liste <T> Wie bekomme ich die Art von T?
List<myclass> myList = dataGenerator.getMyClasses();
lbxObjects.ItemsSource = myList;
lbxObjects.SelectionChanged += lbxObjects_SelectionChanged;
private void lbxObjects_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Reflect();
}
Private void Reflect()
{
foreach (PropertyInfo pi in lbxObjects.SelectedItem.GetType().GetProperties())
{
switch (pi.PropertyType.Name.ToLower())
{
case "list`1":
{
// This works if the List<T> contains one or more elements.
Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));
// but how is it possible to get the Type if the value is null?
// I need to be able to create a new object of the type the generic list expect.
// Type type = pi.getType?? // how to get the Type of the class inside List<T>?
break;
}
}
}
}
private Type GetGenericType(object obj)
{
if (obj != null)
{
Type t = obj.GetType();
if (t.IsGenericType)
{
Type[] at = t.GetGenericArguments();
t = at.First<Type>();
} return t;
}
else
{
return null;
}
}
sollte es nicht Typ itemType = interfaceType.GetGenericArguments sein() [0]; – Muxa
Amüsant schlägt das zweite Beispiel mit, sagen wir 'IList'. Fix unter http://StackOverflow.com/a/13608408/284795 –
Ich weiß, dass die Antwort sehr alt ist, aber ich versuche, Folgendes zu verstehen: 'GetGenericArguments() [0];' Warum gibt es die 0? Gibt es im Type [] immer nur einen Eintrag? – Ismoh