Getting Infinite Loop Issue. Process Terminated due to StackOverflowException?

送分小仙女□ 提交于 2019-12-13 11:30:37

问题


namespace ConsoleApplication1
{

class class1
{
    protected internal string inf1()
    {
        Console.WriteLine("\n......inf1() \n");

        return inf1();
    }
}




class class2 :class1
{
    static void Main(string[] args)
    {
        class1 c1 = new class1();

        class2 c2 = new class2();

        Console.WriteLine(c1.inf1());

        Console.WriteLine(c2.inf1());

        Console.ReadKey();
    }
}

Getting Infinite Loop Issue. Process Terminated due to StackOverflowException ?

How to prevent the code from looping infinitely ?


回答1:


In class2, you are calling Console.WriteLine(c1.inf1());.

So class1.inf1 should return a string as you are trying to output it to the console.

However, class1.inf1() recursively calls itself with no exit and does not return a string.

So I think this may be what you are trying to accomplish:

protected internal string inf1()
{
    return "\n......inf1() \n";
}



回答2:


The problem is here :

protected internal string inf1()
{
    Console.WriteLine("\n......inf1() \n");
    return inf1();
}

This method return a call to itself everytime which mean it will be called indefinitely. The problem with that is that a program before it enter a method add to the stack the current position on memory it is on so that when a method return it can go back to that place and continue from there, but that stack is not infinite and so with your problematic method it become full and the program then crash because without a stack it cannot continue to function.



来源:https://stackoverflow.com/questions/26016613/getting-infinite-loop-issue-process-terminated-due-to-stackoverflowexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!