如何获取嵌套属性

Flo*_*ian 6 c# reflection

我想检索一个PropertyInfo,这里代码:

string propertyName="Text";
PropertyInfo pi = control.GetType().GetProperty(propertyName);
Run Code Online (Sandbox Code Playgroud)

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

string propertyName="DisplayLayout.Override.RowSelectors";
PropertyInfo pi = control.GetType().GetProperty(propertyName);
Run Code Online (Sandbox Code Playgroud)

有没有办法获得嵌套属性?

最好的祝福,

弗洛里安

编辑:我现在有一个新问题,我想得到一个属性是一个数组:

string propertyName="DisplayLayout.Bands[0].Columns";
PropertyInfo pi = control.GetType().GetProperty(propertyName)
Run Code Online (Sandbox Code Playgroud)

谢谢

Are*_*ren 8

是:

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);
}
Run Code Online (Sandbox Code Playgroud)

所谓的:

PropertyInfo pi = GetProp(control.GetType(), "DisplayLayout.Override.RowSelectors");
Run Code Online (Sandbox Code Playgroud)

胜利的递归!