Sto lavorando a un progetto di riflessione e ora sono bloccato. Se ho un oggetto "myclass" che può contenere una lista qualcuno sa come ottenere il tipo come nel codice qui sotto se la proprietà myclass.SomList è vuota?C# elenco generico <T> come ottenere il tipo di 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;
}
}
non dovrebbe essere di tipo itemtype = interfaceType.GetGenericArguments() [0]; – Muxa
In modo divertente, il secondo esempio fallisce con, diciamo 'IList'. Correzione di seguito http://stackoverflow.com/a/13608408/284795 –
So che la risposta è molto vecchia, ma cerco di capire quanto segue: 'GetGenericArguments() [0];' perché c'è lo 0? C'è solo un elemento nel Tipo []? – Ismoh