首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 銳利體驗 (八) (2):索引器實戰應用——位元組陣列優化

     編輯:關於C語言

索引器實戰範例:BitArray 位元陣列

以下範例展示索引器如何為使用者提供友善介面,同時大幅降低儲存空間成本。

using System;
class BitArray
{
    int[] bits;
    int length;
    public BitArray(int length)
    {
        if (length < 0) throw new ArgumentException();
        bits = new int[((length - 1) >> 5) + 1]; // 每 32 位用一個 int 儲存
        this.length = length;
    }
    public int Length { get { return length; } }
    public bool this[int index]
    {
        get
        {
            if (index < 0 || index >= length) throw new IndexOutOfRangeException();
            return (bits[index >> 5] & 1 << index) != 0;
        }
        set
        {
            if (index < 0 || index >= length) throw new IndexOutOfRangeException();
            if (value) bits[index >> 5] |= 1 << index;
            else bits[index >> 5] &= ~(1 << index);
        }
    }
}
class Test
{
    static void Main()
    {
        BitArray Bits = new BitArray(10);
        for (int i = 0; i < 10; i++) Bits[i] = (i % 2) == 0;
        for (int i = 0; i < 10; i++) Console.Write(Bits[i] + " ");
    }
}

輸出:True False True False True False True False True False

設計精華

  • 以 int[] 內部儲存,每個 int (32 位) 容納 32 個布林值,空間效率極高。
  • 索引器 this[int index] 提供類陣列存取介面:Bits[i] = true/false、bool b = Bits[i]。
  • get 透過位元運算 (bits[index >> 5] & 1 << index) != 0 讀取指定位元。
  • set 透過 |= 設定位元、&= ~() 清除位元。
  • 索引器常用於物件容器,為內部物件提供友善存取介面——這也是 C# 將方法包裝成索引器的原因。.NET Framework 類別庫大量應用索引器。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved