【问题标题】:Encapsulating a 1D array field with a 2D array property in C#在 C# 中用二维数组属性封装一维数组字段
【发布时间】: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),所以我不是在寻找一般建议,只是想知道这种特定方法在我使用的语言中是否可行。谢谢!

【问题讨论】:

标签: c# arrays unity3d properties


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 2012-03-08
    • 2011-03-27
    • 1970-01-01
    相关资源
    最近更新 更多