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