簡體   English   中英

如何獲取嵌套屬性

[英]How to get nested properties

我想檢索一個PropertyInfo,這里代碼:

string propertyName="Text";
PropertyInfo pi = control.GetType().GetProperty(propertyName);

它工作正常,但如果我想檢索嵌套屬性,它返回null:

string propertyName="DisplayLayout.Override.RowSelectors";
PropertyInfo pi = control.GetType().GetProperty(propertyName);

有沒有辦法獲得嵌套屬性?

最好的祝福,

弗洛里安

編輯:我現在有一個新問題,我想得到一個屬性是一個數組:

string propertyName="DisplayLayout.Bands[0].Columns";
PropertyInfo pi = control.GetType().GetProperty(propertyName)

謝謝

是:

public PropertyInfo GetProp(Type baseType, string propertyName)
{
    string[] parts = propertyName.Split('.');

    return (parts.Length > 1) 
        ? GetProp(baseType.GetProperty(parts[0]).PropertyType, parts.Skip(1).Aggregate((a,i) => a + "." + i)) 
        : baseType.GetProperty(propertyName);
}

所謂的:

PropertyInfo pi = GetProp(control.GetType(), "DisplayLayout.Override.RowSelectors");

勝利的遞歸!

剛剛做同樣的PropertyType ,你剛剛得到的財產(和重復往往你需要的):

PropertyInfo property = GetType().GetProperty(propertyName);
PropertyInfo nestedProperty = property.PropertyType.GetProperty(nestedPropertyName)

你可以做到,但你必須為每個級別做“整件事”,這意味着:

  • 從您的對象類型獲取屬性
  • 獲取該屬性的類型
  • 沖洗並重復:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM