BitArray类管理一个紧凑的位值数组,这些值表示为布尔值,其中true表示该位打开,即1 ,false表示该位关闭,即0 。此类包含在System.Collections命名空间中。
BitArray.SetAll(Boolean)方法用于将BitArray中的所有位设置为指定值。
特性:
- BitArray类是一个集合类,其中容量始终与计数相同。
- 通过增加Length属性将元素添加到BitArray中。
- 通过减小Length属性来删除元素。
- 可以使用整数索引访问此集合中的元素。此集合中的索引从零开始。
句法:
public void SetAll (bool value);
此处, value是要分配给所有位的布尔值。
注意:此方法是O(n)运算,其中n是Count。
下面的程序说明了BitArray.SetAll(Boolean)方法的用法:
范例1:
// C# code to set all bits in the
// BitArray to the specified value
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a BitArray myBitArr
// Initializing all the values to false
BitArray myBitArr = new BitArray(5, false);
// Printing the values in myBitArr
// It should display all the bits as false
Console.WriteLine("Initially the bits are as : ");
PrintIndexAndValues(myBitArr);
// Setting all bits to true
myBitArr.SetAll(true);
// Printing the values in myBitArr
// It should display all the bits as true
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
False
False
False
False
Finally the bits are as :
True
True
True
True
True
范例2:
// C# code to set all bits in the
// BitArray to the specified value
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);
// Setting all bits to false
myBitArr.SetAll(false);
// Printing the values in myBitArr
// It should display all the bits as false
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
False
False
False
False
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.bitarray.setall?view=netframework-4.7.2