7

我需要为简单的游戏创建一个字段。在第一个版本中,该字段就像 Point[,]- 二维数组。

现在我需要使用 System.Collections.Immutable (这是重要的条件)。我试图谷歌并找不到任何东西,这可以帮助我。我不明白如何创建二维 ImmutableArray(或 ImmutableList)?

4

1 回答 1

11

据我所知,没有等效的矩形阵列,但你可以:

  • 有一个ImmutableList<ImmutableList<Point>>
  • 在您自己的类中包装一个ImmutableList<Point>,以提供跨两个维度的访问。

后者将类似于:

// TODO: Implement interfaces if you want
public class ImmutableRectangularList<T>
{
    private readonly int Width { get; }
    private readonly int Height { get; }
    private readonly IImmutableList<T> list;

    public ImmutableRectangularList(IImmutableList<T> list, int width, int height)
    {
        // TODO: Validation of list != null, height >= 0, width >= 0
        if (list.Count != width * height)
        {
            throw new ArgumentException("...");
        }
        Width = width;
        Height = height;
        this.list = list;
    }

    public T this[int x, int y]
    {
        get
        {
            if (x < 0 || x >= width)
            {
                throw new ArgumentOutOfRangeException(...);
            }
            if (y < 0 || y >= height)
            {
                throw new ArgumentOutOfRangeException(...);
            }
            return list[y * width + x];
        }
    }
}
于 2015-09-19T14:09:09.243 回答