通过字符串路径获取对象值 [英] Get Object value by string path
本文介绍了通过字符串路径获取对象值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串 Member.User.Name
和此实例:
Root root = new Root();
root.Member.User.Name = "user name";
如何从成员 Member.User.Name
例如:
string res = GetDeepPropertyValue(root, "Member.User.Name");
res
将为用户名"
谢谢
推荐答案
尝试一下:
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
而变得复杂时,我们才使用递归.
NOTE: We don't need recursive solution for this because the number of loops is known beforehand. Using foreach
would be more efficient if possible. We use recursion only when the implementation becomes complicated with for - foreach
.
这篇关于通过字符串路径获取对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文