繁体   English   中英

C#Reflection:获取嵌套对象属性

[英]C# Reflection: getting a nested objects properties

我在获取嵌套对象属性时遇到问题。 对于我正在使用的示例,我有2个类:

public class user 
{
  public int _user_id {get; set;}
  public string name {get; set;}
  public category {get; set;}
}

public class category 
{
  public int category_id {get; set;}
  public string name {get; set;}
}

那里很简单,如果我反映其中任何一个,我会得到正确的GetProperties()集合,例如,如果我这样做:

PropertyInfo[] props = new user().GetType().GetProperties();

我将获取属性user_id名称类别 ,如果我这样做:

PropertyInfo[] props = new category().GetType().GetProperties();

我将获得属性category_id类别 ; 这很好用。 但是 ,这是我感到困惑的地方......

如您所见,如果我这样做, category用户的最后一个属性

//this gets me the Type 'category'
Type type = new user().GetType().GetProperties().Last().PropertyType;
//in the debugger, I get "type {Name='category', FullName='category'}"
//so I assume this is the proper type, but when I run this:
PropertyInfo[] props = type.GetType().GetProperties();
//I get a huge collection of 57 properties

知道我搞砸了吗? 可以这样做吗?

通过执行type.GetType()您将获得typeof(Type) ,而不是属性类型。

做就是了

PropertyInfo[] props = type.GetProperties();

获得你想要的属性。

但是,您应该按名称而不是按订单查找属性,因为订单不能保证符合您的预期(请参阅文档 ):

GetProperties方法不以特定顺序返回属性,例如按字母顺序或声明顺序。 您的代码不得依赖于返回属性的顺序,因为该顺序会有所不同。

从类型中删除GetType()。 您正在查看Type类型本身的属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM