使用反射获取班级列表的班级成员

我有一个这样输入的类:

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...
}
java21710397 回答:使用反射获取班级列表的班级成员

您需要这样的东西:

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

https://www.ncbi.nlm.nih.gov/nuccore/NC_011415.1?from=1997353&to=1998831&strand=2

本文链接:https://www.f2er.com/2591719.html

大家都在问