C#: Avoid infinite recursion when traversing object graph

后端 未结 6 1953
心在旅途
心在旅途 2020-12-24 03:17

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 orde

6条回答
  •  不思量自难忘°
    2020-12-24 03:56

    This is a common problem, but the best approach depends on the scenario. An additional problem is that in many cases it isn't a problem visiting the same object twice - that doesn't imply recursion - for example, consider the tree:

    A
    => B
       => C
    => D
       => C
    

    This may be valid (think XmlSerializer, which would simply write the C instance out twice), so it is often necessary to push/pop objects on a stack to check for true recursion. The last time I implemented a "visitor", I kept a "depth" counter, and only enabled the stack checking beyond a certain threshold - that means that most trees simply end up doing some ++/--, but nothing more expensive. You can see the approach I took here.

提交回复
热议问题