首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> C# 入門

C# 索引器詳解:語法、虛擬數組行為、重載與多參數

     編輯:C# 入門

C# 索引器詳解:語法、虛擬數組行為、重載與多參數

索引器讓對象像數組一樣通過 [] 訪問,賦予類「虛擬數組」行為。語法類似屬性但使用 this 關鍵字。

一維索引器語法

public elementType this[int index] {
    get { return internalArray[index]; }
    set { internalArray[index] = value; }
}

完整示例:名稱列表索引器

class IndexedNames {
    private string[] names = new string[10];
    public IndexedNames() { for (int i=0;i<10;i++) names[i]="N.A."; }
    public string this[int index] {
        get { return (index>=0 && index<10) ? names[index] : ""; }
        set { if (index>=0 && index<10) names[index] = value; }
    }
    public int this[string name] {  // 重載:字符串參數
        get { for (int i=0;i<10;i++) if (names[i]==name) return i; return -1; }
    }
}
// 使用
var names = new IndexedNames();
names[0] = "Zara"; names[1] = "Riz";
Console.WriteLine(names[0]);      // Zara
Console.WriteLine(names["Riz"]);  // 1

關鍵特性

  • 無名稱,用 this 代表實例
  • 支援重載:參數類型、數量可異(如 int、string、int,int)
  • 非必須為整數索引,可為任意類型
  • get/set 可單獨實現(只讀/只寫索引器)

索引器讓集合類、矩陣、查找表等數據結構 API 更直觀自然。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved