📜  C#|获取或设置BitArray中特定位置的位的值

📅  最后修改于: 2021-05-29 13:52:55             🧑  作者: Mango

BitArray.Item [Int32]属性用于获取或设置BitArray中特定位置的位的值。

句法:

public bool this[int index] { get; set; }

在此,索引是要获取或设置的值的从零开始的索引。

返回值:返回位置index处的位的布尔值。

异常:如果索引小于零或索引等于或大于Count,则此属性将引发ArgumentOutOfRangeException。

下面的程序说明了上面讨论的属性的用法:

范例1:

// C# program to illustrate the
// BitArray.Item[Int32] Property
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a BitArray myBitArr
        BitArray myBitArr = new BitArray(5);
  
        // Initializing all the bits in myBitArr
        myBitArr[0] = false;
        myBitArr[1] = true;
        myBitArr[2] = true;
        myBitArr[3] = false;
        myBitArr[4] = true;
  
        // Printing the values in myBitArr
        Console.WriteLine("Initially the bits are as : ");
  
        PrintIndexAndValues(myBitArr);
  
        // after using item[int32] property
        // changing the bit value of index 2
        myBitArr[2] = false;
  
        // Printing the values in myBitArr
        Console.WriteLine("Finally the bits are as : ");
  
        PrintIndexAndValues(myBitArr);
    }
  
    // Function to display bits
    public static void PrintIndexAndValues(IEnumerable myArr)
    {
        foreach(Object obj in myArr)
        {
            Console.WriteLine(obj);
        }
    }
}

输出:

Initially the bits are as : 
False
True
True
False
True
Finally the bits are as : 
False
True
False
False
True

范例2:

// C# program to illustrate the
// BitArray.Item[Int32] Property
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a BitArray myBitArr
        BitArray myBitArr = new BitArray(5);
  
        // Initializing all the bits in myBitArr
        myBitArr[0] = true;
        myBitArr[1] = false;
        myBitArr[2] = false;
        myBitArr[3] = false;
        myBitArr[4] = true;
  
        // after using item[int32] property
        // it will give run time error as
        // index is less than zero
        myBitArr[-1] = false;
  
        PrintIndexAndValues(myBitArr);
    }
  
    // Function to display bits
    public static void PrintIndexAndValues(IEnumerable myArr)
    {
        foreach(Object obj in myArr)
        {
            Console.WriteLine(obj);
        }
    }
}

运行时错误:

注意:检索和设置此属性的值是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.bitarray.item?view=netframework-4.7.2