在c#中解决无限递归

时间:2012-09-24 23:58:41

标签: c# recursion stack-overflow callstack

我知道我的代码中存在无限递归问题,堆栈溢出。我只是不知道如何解决它,帮助将不胜感激。

public Point WorldToMapCell(Point worldPoint)
{
    return WorldToMapCell(new Point((int)worldPoint.X, (int)worldPoint.Y));
}

public MapCell GetCellAtWorldPoint(Point worldPoint)
{
    Point mapPoint = WorldToMapCell(worldPoint);
    return Rows[mapPoint.Y].Columns[mapPoint.X];
}

public MapCell GetCellAtWorldPoint(Vector2 worldPoint)
{
    return GetCellAtWorldPoint(new Point((int)worldPoint.X, (int)worldPoint.Y));
}

3 个答案:

答案 0 :(得分:2)

无限递归(以及由此产生的堆栈溢出)发生在你有一个直接或间接地重复调用自身的函数时,没有任何机会让它停止这样做。您的第一个函数WorldToMapCell无条件地调用自身,导致此问题。

答案 1 :(得分:2)

为了使递归起作用,您的方法必须具有基本案例。否则,它将陷入无限循环调用自身。

考虑计算数字的阶乘的情况:

public int factorial(int x) {
    if (x == 0)
        return 1;
    else 
        return x * factorial(x - 1);

为了使递归起作用,因子方法接近基本情况,其中x = 0.在你的方法中,你没有向基本情况采取任何步骤,因此,你的方法将继续自我调用。< / p>

答案 2 :(得分:2)

public Point WorldToMapCell(Point worldPoint)
{
    return WorldToMapCell(new Point((int)worldPoint.X, (int)worldPoint.Y));
}

此方法将无限递归。 (它一遍又一遍地称呼自己。)

据我所知,这个方法应该返回一个带有worldpoint参数的新点的新点,如果是这样,它应该是这样的:

public Point WorldToMapCell(Point worldPoint)
{
    return new Point((int)worldPoint.X, (int)worldPoint.Y);
}

您无需调用该方法,而只需直接返回新点。