在递归期间防止StackOverFlow异常 [英] Prevent StackOverFlow Exception during Recursive

查看:71
本文介绍了在递归期间防止StackOverFlow异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我创建了一个名为ABC的类,其中包含以下属性:

字符串名称;

列表< abc>儿童;

列表< abc>家长;



识别父母和孩子的逻辑。



注意:名称属性是唯一的,没有重复项。



例如:我想为对象(iObj)递归找到所有父项,因为我创建了以下代码,但它抛出了StackOverFlow异常:

Hello all,

I have created one class named ABC with the following properties:
string name;
List<abc> Childrens;
List<abc> Parents;

Logic for identifying Parents and Childrens are there.

Note: name property is unique, no duplicates are there.

Ex: I want to find all parents recursively for object (iObj) for that I have created following code but it throws StackOverFlow exception:

Dictionary<string,List<ABC>> tempParents = new Dictionary<string,List<ABC>>;

private void GetAllParents(ABC iObj, ref Dictionary<string,List<ABC>> tempParents)
{
    foreach (ABC item in iObj.Parents)
    {
        if (!tempParents.Keys.Contains(item.name))
        {
            tempParents.Add(item.name, item);
        }
        
        GetAllParents(item, ref tempParents);
    }
}

=============================



有人可以提供此异常的解决方案,如果是内存异常,是否可以解决它?



即使我没有任何替代方法可以找到所有父母而不是递归。



提前谢谢...

=============================

Can somebody please provide the solution for this exception, if it is memory exception, is it possible to resolve it?

Even I am ok with any alternate way to find all parents instead of recursion .

Thanks in advance...

推荐答案

除了解决方案1之外,使用调试器通常可以帮助找到导致此类问题的原因。您主要必须检查堆栈上每个级别的父级名称,并且在大多数情况下循环发生的位置应该很明显(通常周期不会很长)。



另外,考虑到在填充tempParents时已经检查了重复的项目,因此迁移是一个好主意,在那里放置断点以查看是否出现问题。此外,在这种情况下,您不应该递归调用fumction,因为已经处理了父级。
In addition to solution 1, using a debugger can usually help find the cause of such problems. You mainly have to check parent name for each level on the stack and it should be obvious where looping occurs in most cases (typically cycles won't be very long).

Also given that you already check for duplicate items when filling tempParents, it migth be a good idea to put a breakpoint there to see if something goes wrong. Also, in that case, you should not call the fumction recursively since that parent has already have been processed.


递归应该停在顶级项目上。确保没有创建周期。
Recursion should stop on top level items. Make sure you didn't create cycles.


这篇关于在递归期间防止StackOverFlow异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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