【问题标题】:C# Reflection: getting a nested objects propertiesC# 反射:获取嵌套对象的属性
【发布时间】:2009-05-13 09:14:13
【问题描述】:

我在获取嵌套对象属性时遇到问题。对于我正在使用的示例,我有 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、name 和 category,如果我这样做:

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

我会得到属性category_id和category;这很好用。 但是,这就是我感到困惑的地方......

如您所见,category 是 user 的最后一个属性,如果我这样做的话

//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

知道我在哪里搞砸了吗?这个可以吗?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    通过type.GetType(),您得到的是typeof(Type),而不是属性类型。

    做吧

    PropertyInfo[] props = type.GetProperties();
    

    获取你想要的属性。

    但是,您应该按名称而不是顺序来查找属性,因为不能保证顺序与您期望的一样(请参阅documentation):

    GetProperties 方法不 返回特定的属性 顺序,例如按字母顺序或 申报令。您的代码不得 取决于其中的顺序 属性被返回,因为 顺序不同。

    【讨论】:

    • 我实际上并没有用 .Last() 查找它——这只是为了解释的简单。
    • 很好。由于这些问题已被搜索引擎索引,因此我将按原样发表评论,因为我觉得人们应该意识到必须避免使用该顺序。
    • 哇,这么简单...我只是想得太用功(或者可能还不够),谢谢!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 2011-02-24
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多