是否可以在C#中编写基于规则的迭代器(用于网格中平铺的nieghbours)?

是否可以在C#中编写基于规则的迭代器(用于网格中平铺的nieghbours)?,c#,struct,iterator,pass-by-reference,C#,Struct,Iterator,Pass By Reference,我使用的是C#,我使用了一个2d结构数组作为一个瓷砖网格。这不是关于如何从网格中的瓷砖中找到8个相邻的瓷砖。我知道,在c#中,你可以有一系列的收益率,使一个ienumerable。比如: public IEnumerable<int> fakeList() { yield return 1; yield return 2; } public IEnumerable fakeList() { 收益率1; 收益率2; } 并用foreach循环调用它。现在,在我的gr

我使用的是C#,我使用了一个2d结构数组作为一个瓷砖网格。这不是关于如何从网格中的瓷砖中找到8个相邻的瓷砖。我知道,在c#中,你可以有一系列的收益率,使一个ienumerable。比如:

public IEnumerable<int> fakeList()
{
    yield return 1;
    yield return 2;
}
public IEnumerable fakeList()
{
收益率1;
收益率2;
}
并用foreach循环调用它。现在,在我的grid类中,我想用一种简单的方法访问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
}
公共IEnumerable邻居(int x,int y)
{
if((x+1)>=0&&y>=0&&……)//检查上面的节点是否在网格内
收益率返回网格数组[x+1,y];
//冲洗,每个方向重复7次以上
}
相反,每当我需要邻居时,我需要复制粘贴8if条件,并检查我是否使用正确的x+方向、y+方向来查找有效索引。基本上,这是一种巨大的痛苦

我可以通过以下方式解决:

  • 不使用结构,让我的生活更轻松。以及消除可能的过早优化。但我会在游戏的每一帧都运行这个代码。可能多次。如果可能的话,我想保留结构
  • 为索引编写迭代器。例:
  • 第二种方法有效吗?还是会产生垃圾?我不知道收益率回报是如何运作的

    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
    }
    
    public结构GridTile
    {
    公共int x;
    公共INTZ;
    公共网格块(整数x,整数z)
    {
    这个.x=x;
    这个。z=z;
    }
    }
    公共IEnumerable邻居(int x,int y)
    {
    if((x+1)>=0&&y>=0&&……)//检查右节点是否在内部
    收益率返回新网格块(x+1,y);
    //冲洗,每个方向重复7次以上
    }
    
    如果您知道2D数组项的坐标,则可以使用循环检索相邻项:

    var twoD = new int[10,10];
    
    var someX = 5;
    var someY = 5;
    
    List<int> neighbors = new List<int>();
    
    for(int nx = -1; nx <= 1; nx++){
      for(int ny = -1; ny <= 1; ny++){
        int iX = someX + nX;
        int iY = someY + nY;
        if(iX > 0 && iX < twoD.GetLength(0) && iY > 0 && iY < twoD.GetLength(1))
          neighbors.Add(twoD[iX,iY]);
      }
    }
    
    var twoD=newint[10,10];
    var-someX=5;
    var-someY=5;
    列表邻居=新列表();
    对于(intnx=-1;nx0&&iY
    这是一种更好的方法。至少我不需要担心索引一直保持正确。但是像一个合适的foreach循环是不可能的吗?不太清楚为什么你断言一个
    for
    循环不是一个合适的循环;实际上更多的情况是,
    foreach
    不是一个“适当的”循环,因为它实际上并不存在——它只是连接到迭代器的一个语法糖循环。。但是为什么不
    产生返回twoD[iX,iY]
    ?foreach循环更容易编写。我还想修改这个结构,这样我就不能使用IEnumerators了,我开始搞不清楚你到底想要什么,但是一个参数“foreach更容易写”当a)我们谈论的是大约5个字符的差异,b)按下
    f o r TAB选项卡
    让VS为您编写for循环比等效的
    f o r e a c h选项卡
    更容易时,就没有意义了-请参阅