c# - 获取通过 PropertyDescriptorCollection 循环的 List 项的类型

标签 c# properties propertydescriptor

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

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

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

最佳答案

你可以使用GetGenericArguments方法获取泛型参数,它将返回一个类型数组,你可以只获取第一个类型,即列表中泛型参数的类型:

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

此外,我建议不要通过比较名称来检查属性类型:

if(prop.PropertyType.IsGenericType &&
   prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>))

关于c# - 获取通过 PropertyDescriptorCollection 循环的 List 项的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28213837/

相关文章:

c# - .net mvc select list handle on selected item event

c# - rar和unrar的命令行是什么?

c# - 滑动条拇指尺寸

c# - var 关键字并不总是有效?

c# - 获取类型的默认 PropertyDescriptors

模拟点击链接的C#代码

javascript - 如何从对象子 sibling 访问对象子值?

ios - iOS 中的默认属性

python - 为什么这个装饰器不能从带有 "from module import *"的模块导入?

c# - TypeDescriptor.GetProperties(thisType) 返回只写的属性