1

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

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));
}
4

3 回答 3

2

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

于 2012-09-25T00:01:12.600 回答
2

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

考虑计算一个数的阶乘的情况:

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

为了使递归起作用,阶乘方法接近基本情况,其中 x = 0。在您的方法中,您没有对基本情况采取任何步骤,因此,您的方法将继续永远调用自己。

于 2012-09-25T00:05:29.060 回答
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);
}

您不需要调用该方法,而是直接返回新点。

于 2012-09-25T00:41:45.003 回答