反射,循环抛出类层次结构并按类型查找字段
我有一个大层次结构类,我想循环它的所有属性和子属性等。
示例
public class RootClass
{
// properties ..
List<Item> FirstItemsList { get; set;}
List<Item> SecondItemsList { get; set;}
SubClass SubClass { get; set;}
}
public class SubClass
{
// properties ..
List<Item> ThirdItemsList { get; set;}
}
public class Item
{
//properties
}
我想要一个函数,该函数将返回找到的所有项目类型的列表 即
public IList<Item> GetAllItemsInClass(RootClass entity);
谢谢
I got a Big hierarchic class that i would like to loop all it's properties and sub properties etc..
Example
public class RootClass
{
// properties ..
List<Item> FirstItemsList { get; set;}
List<Item> SecondItemsList { get; set;}
SubClass SubClass { get; set;}
}
public class SubClass
{
// properties ..
List<Item> ThirdItemsList { get; set;}
}
public class Item
{
//properties
}
i want a function that will return me a list of all Item type found
i.e
public IList<Item> GetAllItemsInClass(RootClass entity);
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

如果您需要在一般情况下(任何类层次结构)都可以工作的东西,那么您可以执行以下操作:
您将需要一个递归算法(函数)。该算法将循环成员,将它们的类型添加到列表中(如果尚未添加),然后返回该列表,与刚刚添加到列表中的类型的成员类型相结合 - 在这里您进行递归称呼。终止条件为:
Type.Assembly
检查定义的程序集。如果您需要更简单的东西,请使用上面的技术,但只需在循环中使用 if 语句。
让我知道这是否是您想要的,然后我会在有更多时间时为您发布代码示例。
更新:以下是显示代码示例如何处理类型并递归获取其中包含的所有类型。您可以这样调用它:
List typesHere = GetTypes(myObject.GetType())
因此,当我在您在原始帖子中发布的类上运行此操作时(具有如下两个基本属性的项目),我得到了以下列表:
我没有进行全面的测试,但这至少应该为您指明正确的方向。有趣的问题。我很高兴回答。
If you need something that would work in a general case (any class hierarchy) then you could do the following:
You will need a recursive algorithm (function). The algorithm would loop over the members, adding their types to a list (if they're not already added) and then returning that list, COMBINED with the types of the members of the type just added to the list-here you make the recursive call. The terminating conditions would be:
Type.IsPrimitive
).Type.Assembly
.If you need something simpler, then use the technique above but just use an if statement in the loop.
Let me know if this is what you want or no and then I will post a code sample for you when I have more time.
Update: The following is a code sample showing how you can process a type and recursively get all the types contained within it. You can call it this way:
List typesHere = GetTypes(myObject.GetType())
So when I ran this on the classes you posted in your original post (Item having two primitive properties like below) I got the following list:
I didn't make comprehensive tests but this should at least point you to the right direction. Fun question. I have fun answering.