c# - 使用反射获取类列表的类成员
问题描述
我有一个这样的类:
public class MyClass{
public List<Myclass1> mc {get;set;}
public List<Myclass2> mc2 {get;set;}
}
public class Myclass1{
public string MyString{get;set}
public string Mystring2 {get;set}
}
当我通过反射访问 MyClass 成员时,如何获取 Myclasse1 的属性列表:
foreach (var p in MyClass.GetType().GetProperties()){
//Getting Members of MyClass
//Here i need to loop through the members name of Myclass1, MyClass2,etc...
}
解决方案
你需要这样的东西:
foreach (var p in typeof(MyClass).GetProperties())
{
if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
{
Type listOf = p.PropertyType.GetGenericArguments().First();
}
}
我冒昧地更改MyClass.GetType().
为,typeof(MyClass)
因为我认为这就是您的意思。
基本上我们检查属性类型(例如typeof(List<Myclass1>)
)是从一个 open 创建的List<>
,然后得到第一个通用参数(Myclass1
)。
在线尝试。
推荐阅读
- c# - 当 Interaction.Handle 接收到重复值时,命令引发异常
- javascript - 如何将 JS 循环变量传递给 FireStore 获取
- javascript - 模板组件从数组中移除时不会重新渲染
- powershell - 运行文件夹中的所有 .exe
- node.js - MongoError:doc参数必须是一个对象
- javascript - NodeJS 和 MongoDB 中的多个查询
- python - 在 pip install 上出现无效的语法错误
- mongodb - 由于创建 mongoTemplate bean 错误,Spring boot + mongo Heroku 部署失败
- kubernetes - 使用 AGE 的标签列出 kubernetes pvc
- html - 为什么css不能设置样式带有元素的元素使用css控制图像的大小?