按字符串路径获取对象值

时间:2013-09-18 10:47:12

标签: c# reflection properties

我有这个字符串
Member.User.Name

和这个实例:

Root root = new Root();
root.Member.User.Name = "user name";

如何从成员root

Member.User.Name中提取值

例如:

string res = GetDeepPropertyValue(root, "Member.User.Name");

res将是“用户名”

由于

2 个答案:

答案 0 :(得分:3)

Shazam我相信您希望以递归方式使用反射来访问该属性

public static object GetDeepPropertyValue(object src, string propName)
    {
        if (propName.Contains('.'))
        {
            string[] Split = propName.Split('.');
            string RemainingProperty = propName.Substring(propName.IndexOf('.') + 1);
            return GetDeepPropertyValue(src.GetType().GetProperty(Split[0]).GetValue(src, null), RemainingProperty);
        }
        else
            return src.GetType().GetProperty(propName).GetValue(src, null);
    }

如果需要,请不要忘记添加验证检查。

答案 1 :(得分:1)

试试这个:

public object GetDeepPropertyValue(object instance, string path){
  var pp = path.Split('.');
  Type t = instance.GetType();
  foreach(var prop in pp){
    PropertyInfo propInfo = t.GetProperty(prop);
    if(propInfo != null){
      instance = propInfo.GetValue(instance, null);
      t = propInfo.PropertyType;
    }else throw new ArgumentException("Properties path is not correct");
  }
  return instance;
}
string res = GetDeepPropertyValue(root, "Member.User.Name").ToString();

注意:我们不需要递归解决方案,因为事先已知循环次数。如果可能的话,使用foreach会更有效率。 我们仅在使用for - foreach 的实现变得复杂时才使用递归。

相关问题