本文介绍了C# 泛型列表 <T>如何获得T的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一个反射项目,现在我卡住了.
I'm working on a reflection project, and now I'm stuck.
如果我有一个 myclass
的对象可以保存一个 List
,如果属性 myclass.SomList 是空的?
If I have an object of myclass
that can hold a List<SomeClass>
, does anyone know how to get the type as in the code below if the property myclass.SomList
is empty?
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;
}
}
推荐答案
Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
== typeof(List<>))
{
Type itemType = type.GetGenericArguments()[0]; // use this...
}
更一般地,要支持任何IList
,您需要检查接口:
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()
== typeof(IList<>))
{
Type itemType = type.GetGenericArguments()[0];
// do something...
break;
}
}
这篇关于C# 泛型列表 <T>如何获得T的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!