通过字符串路径获取对象值

Sex*_*yMF 1 c# reflection properties

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

和这个例子:

Root root = new Root();
root.Member.User.Name = "user name";
Run Code Online (Sandbox Code Playgroud)

如何提取root会员的价值Member.User.Name

例如:

string res = GetDeepPropertyValue(root, "Member.User.Name");
Run Code Online (Sandbox Code Playgroud)

res将是“用户名”

谢谢

Kin*_*ing 5

尝试这个:

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

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