C#多维不可变数组

gek*_*k0n 5 c# immutable-collections

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

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

Jon*_*eet 9

据我所知,没有相当于矩形阵列,但你可以:

  • 有一个 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];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)