C# - Multidimensional BitArray

本文关键字:BitArray Multidimensional | 更新日期: 2023-09-27 18:04:05

我试图使用多维BitArray,但我被困在如何设置或读取位与它。

对于正常的一维BitArray,我可以简单地执行以下操作来设置位:

bitArray.Set(0, true);

然而,我不知道如何用二维位数组做同样的事情。例如,下面的代码没有意义,因为Set方法需要索引,但我已经在"[0,0]"中提供了索引:

    bitArray[0, 0].Set(0, true);

我的问题:多维BitArray的正确制作和使用方法是什么?

C# - Multidimensional BitArray

就CLR而言,BitArray的实例不是数组(即BitArray不是"数组类型")。如果你想存储二维位信息,你有几个选项(我所有的例子都创建了一个10x20的二维卷):

a)使用单个BitArray数组,如下所示:

// Init:
BitArray[] storage = new BitArray[ 20 ];
for(int y=0;y<storage.Length;y++) storage[y] = new BitArray( 10, true );
// Usage:
Boolean at5x7 = storage[7][5];

b)使用BitArray本身作为2D空间,通过按行和列索引(这实际上会更快,因为CLR不会经常调用其边界检查):

// Init:
const Int32 width = 10, height = 20;
BitArray storage = new BitArray( width * height );
// Usage:
Boolean at5x7 = storage[ (5 * width) + 7];
public sealed class BitArray2D
{
    private BitArray _array;
    private int _dimension1;
    private int _dimension2;
    public BitArray2D(int dimension1, int dimension2)
    {
        _dimension1 = dimension1 > 0 ? dimension1 : throw new ArgumentOutOfRangeException(nameof(dimension1), dimension1, string.Empty);
        _dimension2 = dimension2 > 0 ? dimension2 : throw new ArgumentOutOfRangeException(nameof(dimension2), dimension2, string.Empty);
        _array = new BitArray(dimension1 * dimension2);
    }
    public bool Get(int x, int y) { CheckBounds(x, y); return _array[y * _dimension1 + x]; }
    public bool Set(int x, int y, bool val) { CheckBounds(x, y); return _array[y * _dimension1 + x] = val; }
    public bool this[int x, int y] { get { return Get(x, y); } set { Set(x, y, value); } }
    private void CheckBounds(int x, int y)
    {
        if (x < 0 || x >= _dimension1)
        {
            throw new IndexOutOfRangeException();
        }
        if (y < 0 || y >= _dimension2)
        {
            throw new IndexOutOfRangeException();
        }
    }
}