C#:遍历对象图时,应避免无限递归 [英] C#: Avoid infinite recursion when traversing object graph

查看:219
本文介绍了C#:遍历对象图时,应避免无限递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象图,其中每个子对象包含引用回到其父属性。是否有无视父母的引用,以避免无限递归什么好的策略?我曾考虑增加一个特殊的[家长]属性,这些属性或使用特殊的命名约定,但也许有更好的方法。

I have an object graph wherein each child object contains a property that refers back to its parent. Are there any good strategies for ignoring the parent references in order to avoid infinite recursion? I have considered adding a special [Parent] attribute to these properties or using a special naming convention, but perhaps there is a better way.

推荐答案

如果环可以推广(你可以有任意数量的组成回路的元素),你可以保持您在已经看到物体的轨道 HashSet的和停止,如果对象是已经在设置,当你访问它。或标志添加到您,当您访问其设置的对象(但你必须要回去和放大器;未设置所有的标志,当你做的,而图只能由单个线程在同一时间内走过)。

If the loops can be generalised (you can have any number of elements making up the loop), you can keep track of objects you've seen already in a HashSet and stop if the object is already in the set when you visit it. Or add a flag to the objects which you set when you visit it (but you then have to go back & unset all the flags when you're done, and the graph can only be traversed by a single thread at a time).

另外,如果环路将只回父,则可以保持在该参考回到它的属性对父的引用,而不是环

Alternatively, if the loops will only be back to the parent, you can keep a reference to the parent and not loop on properties that refer back to it.

为了简单起见,如果你知道父母的参考都会有一定名字,你可以只在该属性不循环:)

For simplicity, if you know the parent reference will have a certain name, you could just not loop on that property :)

这篇关于C#:遍历对象图时,应避免无限递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆