如何遍历类属性树? [英] How to loop through class properties tree?
本文介绍了如何遍历类属性树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class ClassA
{
public ClassB myProp {get;set;}
}
class ClassB
{
public ClassC anotherProp {get;set;}
}
class ClassC
{
public string Name {get;set;}
}
我有一个ClassA类型的对象.如何通过反射递归地迭代以获得ClassC的Name属性值?
I have an object of the ClassA type. How, by the reflection iterate recursively to get ClassC's Name property value ?
推荐答案
好的,解决了.假设我有要获取的值的属性的路径:
Ok, solved. Let's say that I have the path to the Property which value I wanna get:
ClassB.ClassC.Name
然后,在分割了parh之后,我无需递归就遍历了树;)
then, after splitting that parh I iterate through the tree without recursion ;)
var dataPath = column.SortMemberPath.Split(new char[] { '.' });
[...]
foreach (var item in (System.Collections.IList)myObject)
{
var newItem = item;
foreach (var path in dataPath)
{
var actalValue = newItem.GetType().GetProperty(path).GetValue(newItem, null);
newItem = actalValue; //it does the trick
}
now, the newItem is my wanted property value
}
这篇关于如何遍历类属性树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文