使用反射获取类列表的类成员

问题描述 投票:-1回答:1

我有一个这样输入的类:

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
1个回答
0
投票

您需要这样的东西:

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>))是从打开的List<>创建的,然后获取第一个通用参数(Myclass1)。

Try it online

© www.soinside.com 2019 - 2024. All rights reserved.