我正在使用C#,并且使用了二维结构数组来构建图块网格,这与如何从网格中的图块中查找8个相邻图块无关。我知道在C#中,您可以通过一系列收益率产生可数的收益。喜欢:
public IEnumerable<int> fakeList()
{
yield return 1;
yield return 2;
}
并使用foreach循环调用它。现在,在我的网格类中,希望有一种简单的方法来访问并修改grid.array [x,y]中的邻居。但是由于它是一个结构,所以我不能编写像这样的迭代器:
public IEnumerable<int> neighbours(int x,int y)
{
if((x+1) >=0 && y >=0 && .....)//check if node above is inside grid
yield return grid.array[x+1,y];
//rinse and repeat 7 more times for each direction
}
相反,每次我需要邻居时,都需要复制粘贴8if条件,并检查我是否使用正确的x + direction,y + direction查找有效索引。基本上,这是一个巨大的痛苦。
我可以解决:
- 不使用结构,使我的生活更轻松。并摆脱可能的过早优化。但是我要在游戏的每一帧都运行此代码。可能多次。所以我想尽可能保留这些结构。
- 写索引的迭代器。例如:
第二种方法有效吗?还是会产生垃圾?我不知道收益率回报如何详细工作。
public struct GridTile
{
public int x;
public int z;
public GridTile(int x,int z)
{
this.x = x;
this.z = z;
}
}
public IEnumerable<int> neighbours(int x,int y)
{
if ((x + 1) >= 0 && y >= 0 && .....)//check if right node is inside
yield return new Gridtile(x + 1,y);
//rinse and repeat 7 more times for each direction
}