2014-09-24 75 views
-7
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(); 
    } 
} 

获取无限循环问题。进程因StackOverflowException而终止?获取无限循环问题。进程由于StackOverflowException而终止?

如何防止代码无限循环?

+5

是的,inf1被递归调用,因此导致无限循环,所以堆栈溢出是预期的行为。你的问题是什么,或者你不明白什么? – 2014-09-24 12:12:58

+3

你的代码显然有无限递归,方法inf1总是执行自己,你期望发生什么? – 2014-09-24 12:13:24

+1

这是什么意思?你想要在父类中调用一个方法吗? – Luaan 2014-09-24 12:17:17

回答

0

class2,你打电话给Console.WriteLine(c1.inf1());

因此class1.inf1应该返回一个字符串,因为您试图将其输出到控制台。

但是,class1.inf1()以无退出的方式递归调用自身并且不返回字符串。

所以我觉得这可能是你所要完成的任务:

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

感谢您的帮助。现在我已经理解了无限循环背后的原因。 – sunil 2014-09-24 12:25:50

0

的问题是在这里:

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

这个方法返回一个调用本身每次这意味着它会被称为无限期。问题在于,程序在进入方法之前会将当前在内存中的位置添加到堆栈中,以便当方法返回时它可以返回到那个地方并从那里继续,但该堆栈并非无限且所以你的问题方法会变得完整,程序会崩溃,因为没有堆栈它不能继续运行。