简体   繁体   English

用 C# 编写的递归解释器中的 StackOverflowException

[英]StackOverflowException in recursive interpreter written in C#

I'm trying to create a simple interpreter in C#.我正在尝试在 C# 中创建一个简单的解释器。 My idea was using recursion.我的想法是使用递归。 So i have this function:所以我有这个 function:

void InterpretLine(int lineIndex, string[] lines)
{
    // Do interpreter stuff

    InterpretLine(lineIndex + 1, lines);
}

As you can see this uses recursion.如您所见,这使用递归。 I did this using recursion because then i wouldn't have to deal with function stacks and stuff.我使用递归来做到这一点,因为这样我就不必处理 function 堆栈和其他东西了。 This works for less than 100 lines of input code, but if it reaches too much lines, this throws a System.StackOverflowException .这适用于少于 100 行的输入代码,但如果它达到太多行,则会引发System.StackOverflowException

Are there any better ways instead of recursion?有没有比递归更好的方法?

You are going to have to change your logic to not use recursion for reading each line.您将不得不更改逻辑以不使用递归来读取每一行。 If you use recursion you will add a new function call to the stack for every layer of recursion, and the prior function calls will not be removed until the exit condition is met.如果您使用递归,您将为每一层递归添加一个新的 function 调用到堆栈中,并且在满足退出条件之前不会删除之前的 function 调用。 If you make it 500 or so calls deep you can expect a stackoverflow exception.如果您将其设置为 500 次左右的深度调用,您可能会遇到 stackoverflow 异常。

Now, I don't have time to read over your code, but I can tell you what you need to do: Turn your recursive call into a loop.现在,我没有时间阅读您的代码,但我可以告诉您需要做什么:将递归调用变成循环。

Your code can probably be broken down into something like this:您的代码可能可以分解为以下内容:

void ExecuteProgramLine(int lineNumber)
{
   InterpretAndRunLine(lineNumber);
   ExecuteProgramLine(lineNumber + 1);
}

You will want to convert that to this:您需要将其转换为:

for(int lineNumber = 0; lineNumber < fileLines) // (foreach loop is probably better)
{
    InterpretAndRunLine(lineNumber);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM