在for循环中传递带返回值类型的Method

时间:2014-01-28 16:08:56

标签: c#

好的,伙计们,我对这件事情有点困惑。我将向您展示我遇到的问题。

所以我有一个CellMap类,它有这个方法:

public Vector3 GetFreeCell()
{
    Vector3 result = new Vector3();

    if (mOccupiedPoint != null)
    {
        result = (Vector3)mOccupiedPoint[0];

        mOccupiedPoint.RemoveAt(0);
    }

    return result;
}

接下来我的WorldMap类有这个方法:

private void AddObject(GameObjectBase obj, int times, Vector3 position)
{
    for (int i = 0; i < times; i++)
    {
        Vector3 tempPos = position;

        AddObject(obj, tempPos);
    }
}

所以现在我在我的AddObject方法中传递Vector3参数GetFreeCell(),如下所示:

private CellMap mCellMap;

public WorldMap()
{
    CreateCellMap(100, 1, 100);

    AddObject(new DarkForestTreeA(), 1000, mCellMap.GetFreeCell());

}

我从mCellMap.GetFreeCell()获得相同的旧Vector3值。我可以更改AddObject()方法,如:

private void AddObject(GameObjectBase obj, int times)
{
    for (int i = 0; i < times; i++)
    {

        AddObject(obj, mCellMap.GetFreeCell());
    }
}

但我想保留Vector3参数。 有人可以帮助我,并给我一个提示,如何使GetFreeCell()方法在for循环中执行,但只将其作为参数传递?

3 个答案:

答案 0 :(得分:3)

您的问题有点令人困惑,但如果我理解您的要求,您希望将函数(在本例中为GetFreeCell)传递给AddObject,这将被调用{{1} } 多次。在这种情况下,请使用delegate

times

答案 1 :(得分:0)

这是你要找的吗?

private void AddObject(GameObjectBase obj, int times, Vector3 position)
{
    for (int i = 0; i < times; i++)
    {
        Vector3 tempPos = mCellMap.GetFreeCell();

        AddObject(obj, tempPos);
    }
}

答案 2 :(得分:0)

您不能传入一个对象,只是为每次使用更新它自己。

您可以将函数传递给方法,并使用它来获取每次迭代的位置:

private void AddObject(GameObjectBase obj, int times, Func<Vector3> getPosition)
{
    for (int i = 0; i < times; i++)
    {
        Vector3 tempPos = getPosition();

        AddObject(obj, tempPos);
    }
}

您可以使用lambda表达式为函数调用它:

AddObject(new DarkForestTreeA(), 1000, () => mCellMap.GetFreeCell());

一个更棘手的解决方案是发送一个“魔术”对象,在使用时将自身转换为Vector3,并且每次都返回一个新值:

public class MagicVector3 {

  private Func<Vector3> _getVector;

  public MagicVector3(Func<Vector3> getVector) {
    _getVector = getVector;
  }

  public static implicit operator Vector3(MagicVector3 magic) {
    return magic._getVector();
  }

}

现在,您只需将Vector3参数更改为MagicVector3,然后使用以下命令进行调用:

AddObject(new DarkForestTreeA(), 1000, new MagicVector3(() => mCellMap.GetFreeCell()));

但是这段代码有点代码味道。通常你不会使用这样的值,因为它隐藏了实际发生的事情。