Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

คุณสมบัติ Item ของ BitArray Class ใน C#

คุณสมบัติ Item ของ BitArray ใน C#

BitArray แทนอาร์เรย์ของ Bit (Boolean Values) คุณสมบัติ Item[int index] (Indexer) ใช้ Get/Set ค่า Bit ที่ Index ที่กำหนด

ไวยากรณ์


// Get
bool value = bitArray[index];

// Set
bitArray[index] = true; // หรือ false

ตัวอย่างการใช้งาน


using System;
using System.Collections;

class Demo
{
    static void Main()
    {
        // สร้างจาก bool[]
        bool[] boolArray = new bool[5];
        boolArray[0] = true;
        boolArray[1] = true;
        boolArray[2] = false;
        boolArray[3] = false;
        boolArray[4] = false; // Default false
        
        BitArray bitArray = new BitArray(boolArray);
        
        // วนลูปแสดงค่าทั้งหมด
        Console.WriteLine("All bits:");
        foreach (bool b in bitArray)
            Console.WriteLine(b);
        
        // เข้าถึงผ่าน Indexer (Item Property)
        bool secondBit = bitArray[1]; // Index 1 = ตัวที่ 2
        Console.WriteLine($"\nValue of 2nd element (index 1): {secondBit}");
        
        // Set ค่าใหม่
        bitArray[3] = true;
        Console.WriteLine($"Bit at index 3 after set: {bitArray[3]}");
        
        // Properties อื่นๆ
        Console.WriteLine($"Length: {bitArray.Length}");
        Console.WriteLine($"Count: {bitArray.Count}");
    }
}

ผลลัพธ์


All bits:
True
True
False
False
False

Value of 2nd element (index 1): True
Bit at index 3 after set: True
Length: 5
Count: 5

เมธอดอื่นๆ ของ BitArray

Methodคำอธิบาย
And(BitArray)Bitwise AND
Or(BitArray)Bitwise OR
Xor(BitArray)Bitwise XOR
Not()Bitwise NOT (Invert)
SetAll(bool)ตั้งค่าทุก Bit
Get(index)เหมือน Indexer
Set(index, bool)เหมือน Indexer Set
CopyTo(Array, index)Copy ไป Array

ประโยชน์ของ BitArray

  • Memory Efficient: 1 Bit ต่อค่า (vs bool 1 Byte)
  • Bitwise Operations เร็ว (Hardware Level)
  • เหมาะสำหรับ Flags, Bitmasks, Bloom Filters, Sieve of Eratosthenes