【发布时间】:2021-03-07 23:13:18
【问题描述】:
我有一个类,它包含一个公共二维数组作为其接口的一部分:
public Vector2Int MazeSize { get; }
public MazeCellDescriptor[,] wallGrid { get; }
我需要序列化这个类,而我们使用的序列化器无法处理多维数组*(哎呀!)
我可以创建一个函数来访问数组元素...
public Vector2Int MazeSize { get; }
private MazeCellDescriptor[] wallGrid;
public MazeCellDescriptor getWall (int x, int y) => this.wallGrid[x + (y * this.MazeSize.x)];
...但它会破坏我现有的界面。理想情况下,我只需定义一个二维数组属性并将其转换为背面的一维数组,无需更改公共接口。这似乎是最 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),所以我不是在寻找一般建议,只是想知道这种特定方法在我使用的语言中是否可行。谢谢!
【问题讨论】:
-
你可以添加一个带有 indexer 属性的新类型;
public T this[int x, int y] { get => ...; set => ...; }docs.microsoft.com/en-us/dotnet/csharp/programming-guide/… -
@JeremyLakeman 谢谢,这正是我想要的!
标签: c# arrays unity3d properties