如何使这更干净

时间:2018-04-18 10:34:33

标签: c# refactoring

我有很多像这样的代码通过数组迭代

void GetSpawnablePosition() {
    Vector2[] coordX = { Vector2.up, Vector2.down };
    Vector2[] coordY = { Vector2.left, Vector2.right };

    for (int i = 0; i < coordY.Length; i++)
    {
        Vector2[] newArray = new Vector2[enemyGrid.grid[0].Length - 2];

        if (coordY[i] == Vector2.left)
        {
            for (int j = 0; j < enemyGrid.grid[0].Length - 2; j++)
            {
                newArray[j] = new Vector2(0, j+1);
            }
        }

        if (coordY[i] == Vector2.right)
        {
            for (int j = 0; j < enemyGrid.grid[0].Length - 2; j++)
            {
                newArray[j] = new Vector2(enemyGrid.grid[0].Length - 1, j + 1);
            }
        }
        spawnablePosition.Add(coordY[i], newArray);
    }

    for (int i = 0; i < coordY.Length; i++)
    {
        Vector2[] newArray = new Vector2[enemyGrid.grid.Length - 1];

        if (coordX[i] == Vector2.down)
        {
            for (int j = 0; j <= enemyGrid.grid.Length - 2; j++)
            {
                newArray[j] = new Vector2(j+1,0);
            }
        }
        if (coordX[i] == Vector2.up)
        {
            for (int j = 0; j <= enemyGrid.grid.Length - 2; j++)
            {
                newArray[j] = new Vector2(j + 1, enemyGrid.grid[0].Length - 1);
            }
        }

        spawnablePosition.Add(coordX[i], newArray);
    }
}

该片段应该采用网格的索引x和y

https://i.stack.imgur.com/qBJ1T.png

把它放在像这样的字典中

Vector2.up => [[0][1],[0][2],[0][3],[0][4],[0][5]]
Vector2.left=> [[1][0],[2][0],[3][0],[4][0],[5][0]]
Vector2.right=> [[1][6],[2][6],[3][6],[4][6],[5][6]]
Vector2.down=> [[6][1],[6][2],[6][3],[6][4],[6][5]]

我试图对其进行重构以使其更小或更清晰,但实际上,我真的无法找到一个很好的解决方案来使这个大事做得更小。

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

类似的东西:

var yLength = enemyGrid.grid[0].Length;
var xLength = enemyGrid.grid.Length;

spawnablePosition.Add(Vector2.left,  Enumerable.Range(1, yLength).Select(y => new Vector2(0, y)).ToArray());            
spawnablePosition.Add(Vector2.right, Enumerable.Range(1, yLength).Select(y => new Vector2(xLength - 1, y)).ToArray());            
spawnablePosition.Add(Vector2.up,    Enumerable.Range(1, xLength).Select(x => new Vector2(x, 0)).ToArray());            
spawnablePosition.Add(Vector2.down,  Enumerable.Range(1, xLength).Select(x => new Vector2(x, yLength - 1)).ToArray());

确保我不会弄乱相应的数组长度。