C# 多维不可变数组
C# multidimensional immutable array
我需要为简单的游戏创建一个字段。在第一个版本中,该字段类似于 Point[,]
- 二维数组。
现在我需要使用 System.Collections.Immutable(这是重要条件)。我试图 google 但找不到任何可以帮助我的东西。我不明白如何创建二维 ImmutableArray(或 ImmutableList)?
据我所知,没有矩形阵列的等价物,但您可以:
- 有一个
ImmutableList<ImmutableList<Point>>
- 将单个
ImmutableList<Point>
包裹在您自己的 class 中以提供跨维度的访问。
后者类似于:
// 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];
}
}
}
我需要为简单的游戏创建一个字段。在第一个版本中,该字段类似于 Point[,]
- 二维数组。
现在我需要使用 System.Collections.Immutable(这是重要条件)。我试图 google 但找不到任何可以帮助我的东西。我不明白如何创建二维 ImmutableArray(或 ImmutableList)?
据我所知,没有矩形阵列的等价物,但您可以:
- 有一个
ImmutableList<ImmutableList<Point>>
- 将单个
ImmutableList<Point>
包裹在您自己的 class 中以提供跨维度的访问。
后者类似于:
// 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];
}
}
}