堆栈溢出错误 - C#

时间:2015-01-29 14:01:34

标签: c# stack-overflow

我一直收到堆栈溢出错误,但我无法弄清楚为什么或如何解决它。这是我的代码:

 private void ShowDiff(int leftIndex, int rightIndex)
        {
            if (leftIndex > 0 && rightIndex > 0 &&
                _compareFunc(_left[_preSkip + leftIndex - 1], _right[_preSkip + rightIndex - 1]))
            {
                ShowDiff(leftIndex - 1, rightIndex - 1);
                FireLineUpdate(DiffType.None, _preSkip + leftIndex - 1, -1);
            }
            else
            {
                if (rightIndex > 0 &&
                    (leftIndex == 0 ||
                     _matrix[leftIndex, rightIndex - 1] >= _matrix[leftIndex - 1, rightIndex]))
                {
                    ShowDiff(leftIndex, rightIndex - 1);
                    FireLineUpdate(DiffType.Inserted, -1, _preSkip + rightIndex - 1);
                }
                else if (leftIndex > 0 &&
                         (rightIndex == 0 ||
                          _matrix[leftIndex, rightIndex - 1] < _matrix[leftIndex - 1, rightIndex]))
                {
                    ShowDiff(leftIndex - 1, rightIndex);
                    FireLineUpdate(DiffType.Deleted, _preSkip + leftIndex - 1, -1);
                }
            }

        }

这是我不断得到的错误:

未处理的类型&#39; System.StackOverflowException&#39;发生在Comparer.exe

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

编辑:如果没有条件,则添加中断。


相反,使用循环重写函数。此外,您可以稍微简化一下逻辑。

注意:leftIndexrightIndex都大于0的假设仍然存在。

 private void ShowDiff(int leftIndex, int rightIndex)
 {
     while(leftIndex > 0 && rightIndex > 0)
     {
         if (leftIndex > 0 && rightIndex > 0 &&
                _compareFunc(
                    _left[_preSkip + leftIndex - 1],
                    _right[_preSkip + rightIndex - 1]))
         {
             leftIndex--;
             rightIndex--;
             FireLineUpdate(
                 DiffType.None,
                 _preSkip + leftIndex - 1,
                 -1);
         }
         else
         {
             if (rightIndex > 0 &&
                    (_matrix[leftIndex, rightIndex - 1] >=
                        _matrix[leftIndex - 1, rightIndex]))
             {
                 rightIndex--;
                 FireLineUpdate(
                     DiffType.Inserted,
                     -1,
                     _preSkip + rightIndex - 1);
             }
             else if (_matrix[leftIndex, rightIndex - 1] <
                         _matrix[leftIndex - 1, rightIndex]))
             {
                 leftIndex--;
                 FireLineUpdate(
                     DiffType.Deleted,
                     _preSkip + leftIndex - 1,
                     -1);
             }
             else
             {
                 break;
             }
         }
     }
 }