C# 使用反射获取类列表的类成员
我有这样一个类:C# 使用反射获取类列表的类成员,c#,system.reflection,C#,System.reflection,我有这样一个类: 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} } foreach (var p in typeo
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}
}
foreach (var p in typeof(MyClass).GetProperties())
{
if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
{
Type listOf = p.PropertyType.GetGenericArguments().First();
}
}
你需要这样的东西:
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}
}
foreach (var p in typeof(MyClass).GetProperties())
{
if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
{
Type listOf = p.PropertyType.GetGenericArguments().First();
}
}
foreach(typeof(MyClass).GetProperties()中的var p)
{
if(p.PropertyType.IsGenericType&&p.PropertyType.GetGenericTypeDefinition()==typeof(列表))
{
类型listOf=p.PropertyType.GetGenericArguments().First();
}
}
我已经冒昧地将MyClass.GetType().
更改为typeof(MyClass)
,因为我认为这就是你的意思
基本上,我们检查属性类型(例如,typeof(List)
)是否是从打开的列表创建的,然后获取第一个通用参数(Myclass1
)