2

循环遍历泛型类型的属性T,我想知道是否T恰好是List该列表包含的项目类型。

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in properties)
       if (prop.PropertyType.Name.Equals("List`1"))
       ???

我可以使用上面的代码检测类型是否为 a List,但是如何获取列表项的类型?

4

1 回答 1

2

You can get the generic arguments use GetGenericArguments method, it will return an array of types, you can just get the first type which is the type of generic argument of your list:

var type = prop.PropertyType.GetGenericArguments()[0];

Also instead of comparing names to check property type I would suggest this way:

if(prop.PropertyType.IsGenericType &&
   prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
于 2015-01-29T11:43:47.423 回答