C#反射获取实体类及引用实体属性和名称
public class A
{
private List<B> head = new List<B>();
public List<B> Head
{
get { return head; }
set { head = value; }
}
}
public class B
{
public int Id{ get; set; }
public string Name{ get; set; }
}
现在可以获取A里面的名称,就是获取不了B里面的,因为List<B>无法反射到B类,该怎么办
就是要获取 head Id Name 这三个名称都要获取到
满意200分全给,肯定结贴 反射?实体名称属性
[解决办法]
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
var typeA = Type.GetType("ConsoleApplication1.A");
Console.WriteLine(typeA.Name);
var propertyHead = typeA.GetProperty("Head");
if (propertyHead.PropertyType.IsGenericType) {
if (propertyHead.PropertyType.GenericTypeArguments.Length > 0) {
var typeB = propertyHead.PropertyType.GenericTypeArguments[0];
Console.WriteLine(typeB.Name);
foreach(var each in typeB.GetProperties()){
Console.WriteLine(each.Name);
}
}
}
Console.WriteLine("press any key to exit.");
Console.ReadLine();
}
}
public class A {
private List<B> head = new List<B>();
public List<B> Head {
get { return head; }
set { head = value; }
}
}
public class B {
public int Id { get; set; }
public string Name { get; set; }
}
}