如何通过名称获取实体的子属性

Omi*_*-RH 2 c#

在类Person中我与类Position有关系,类Position与类PositionTitle有关系,而PositionTitle有一个名为Title的属性

public class Person
{
   public Position Position{get;set;}
}

public class Position
{
   public PositionTitle PositionTitle{get;set;}
}

public class PositionTitle 
{
   public string Title{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

我有一个字符串"Person.Position.PositionTitle.Title",我怎么能用这个字符串得到这个人的属性?

Jon*_*eet 6

您需要按点分割字符串,然后使用反射按名称获取每个属性.您可以使用- 获取属性的类型PropertyInfo.PropertyType - 然后使用它来获取链中的下一个属性.像这样的东西:

public object GetProperty(object source, string path)
{
    string[] bits = path.Split('.');
    Type type = source.GetType(); // Or pass this in
    object result = source;
    foreach (string bit in bits)
    {
        PropertyInfo prop = type.GetProperty(bit);
        type = prop.PropertyType;
        result = prop.GetValue(result, null);
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

你可能想要调整这个绑定标志等,但这是正确的基本想法.