【问题标题】:Solve Infinite Recursion in c#在 C# 中解决无限递归
【发布时间】:2012-09-16 11:23:23
【问题描述】:

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

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

【问题讨论】:

  • 您需要一种终止方式!通常是基本情况。

标签: c# recursion stack-overflow callstack


【解决方案1】:

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

【讨论】:

  • 那么,我必须在退货上加上一个条件?
  • 好吧,我不一定会这么说。 WorldToMapCell 应该做什么?它应该调用自己(这实际上没有意义),还是应该调用其他函数?你甚至需要这个功能吗?
【解决方案2】:

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

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

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

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

【讨论】:

  • 虽然这个答案是正确的,但我认为它与问题中的原始问题根本没有太大关系。
【解决方案3】:
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);
}

不需要调用方法,直接返回新点即可。

【讨论】:

    猜你喜欢
    • 2015-05-21
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    相关资源
    最近更新 更多