Getting Infinite Loop Issue. Process Terminated du

2019-09-22 11:29发布

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 ?

2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-22 12:02

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";
}
查看更多
▲ chillily
3楼-- · 2019-09-22 12:08

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.

查看更多
登录 后发表回答