繁体   English   中英

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

[英]StackOverflowException in recursive interpreter written in C#

我正在尝试在 C# 中创建一个简单的解释器。 我的想法是使用递归。 所以我有这个 function:

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

    InterpretLine(lineIndex + 1, lines);
}

如您所见,这使用递归。 我使用递归来做到这一点,因为这样我就不必处理 function 堆栈和其他东西了。 这适用于少于 100 行的输入代码,但如果它达到太多行,则会引发System.StackOverflowException

有没有比递归更好的方法?

您将不得不更改逻辑以不使用递归来读取每一行。 如果您使用递归,您将为每一层递归添加一个新的 function 调用到堆栈中,并且在满足退出条件之前不会删除之前的 function 调用。 如果您将其设置为 500 次左右的深度调用,您可能会遇到 stackoverflow 异常。

现在,我没有时间阅读您的代码,但我可以告诉您需要做什么:将递归调用变成循环。

您的代码可能可以分解为以下内容:

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

您需要将其转换为:

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