首页 > 解决方案 > 使用反射获取类列表的类成员

问题描述

我有一个这样的类:

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...
}

标签: c#system.reflection

解决方案


你需要这样的东西:

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)。

在线尝试


推荐阅读