在C#中用二维数组属性封装一维数组字段

Encapsulating a 1D array field with a 2D array property in C#

我有一个 class,其中包含一个 public 二维数组作为其界面的一部分:

public Vector2Int MazeSize { get; }
public MazeCellDescriptor[,] wallGrid { get; }

我需要序列化这个 class,而我们使用的序列化程序无法处理多维数组*(糟糕!)

我可以创建一个函数来访问数组元素...

    public Vector2Int MazeSize { get; }
    private MazeCellDescriptor[] wallGrid;
    public MazeCellDescriptor getWall (int x, int y) => this.wallGrid[x + (y * this.MazeSize.x)];

... 但它会破坏我现有的界面。理想情况下,我只定义一个二维数组 属性 并在背面将其转换为一维数组,无需更改 public 界面。这似乎是最 OOO 的解决方案,但我不确定是否可行,我只是语法错误,或者没有办法做到这一点。

public MazeCellDescriptor[int x, int y] WallGrid => this.wallGrid[x + (y * this.MazeSize.x)];
public MazeCellDescriptor[,] WallGrid[int x, int y] => this.wallGrid[x + (y * this.MazeSize.x)];
// or something like that, neither of these compile...

*对于上下文,这是一个 Unity 游戏项目。我找到了一些可能的解决方案(更改界面,或 converting the array before serializing),所以我不是在寻找一般性建议,只是想知道这种特定方法是否适用于我使用的语言。谢谢!

我想你尝试的差不多了。您可以简单地使用 属性,例如

public MazeCellDescriptor this[int x, int y]
{
    get => this.wallGrid[x + (y * this.MazeSize.x)];
    set
    {
        this.wallGrid[x + (y * this.MazeSize.x)] = value;
    }
}