簡體   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