我正在做一个反射项目,现在我被卡住了。
如果我有一个可以保存List<SomeClass>
的myclass
对象,如果myclass.SomList
属性为空,谁知道如何获得下面代码中的类型?
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;
}
}
发布于 2009-06-25 13:52:29
Marc的回答是我使用的方法,但为了简单(以及更友好的API?)如果您有一个属性,可以在集合基类中定义一个属性,例如:
public abstract class CollectionBase<T> : IList<T>
{
...
public Type ElementType
{
get
{
return typeof(T);
}
}
}
我发现这种方法很有用,对于任何泛型的新手来说都很容易理解。
https://stackoverflow.com/questions/1043755
复制相似问题