
- C# 基礎教程
- C# - 首頁
- C# - 概述
- C# - 環境
- C# - 程式結構
- C# - 基本語法
- C# - 資料型別
- C# - 型別轉換
- C# - 變數
- C# - 常量
- C# - 運算子
- C# - 決策
- C# - 迴圈
- C# - 封裝
- C# - 方法
- C# - 可空型別
- C# - 陣列
- C# - 字串
- C# - 結構體
- C# - 列舉
- C# - 類
- C# - 繼承
- C# - 多型
- C# - 運算子過載
- C# - 介面
- C# - 名稱空間
- C# - 預處理器指令
- C# - 正則表示式
- C# - 異常處理
- C# - 檔案 I/O
C# - 索引器
索引器允許像陣列一樣對物件進行索引。當您為類定義索引器時,此類表現得類似於虛擬陣列。然後,您可以使用陣列訪問運算子([ ])訪問此類的例項。
語法
一維索引器具有以下語法:
element-type this[int index] { // The get accessor. get { // return the value specified by index } // The set accessor. set { // set the value specified by index } }
索引器的使用
索引器的行為宣告在某種程度上類似於屬性。與屬性類似,您可以使用get和set訪問器來定義索引器。但是,屬性返回或設定特定的資料成員,而索引器則返回或設定物件例項中的特定值。換句話說,它將例項資料分解成更小的部分併為每個部分編制索引,獲取或設定每個部分。
定義屬性涉及提供屬性名稱。索引器不是用名稱定義的,而是使用this關鍵字,它指的是物件例項。下面的示例演示了這個概念:
using System; namespace IndexerApplication { class IndexedNames { private string[] namelist = new string[size]; static public int size = 10; public IndexedNames() { for (int i = 0; i < size; i++) namelist[i] = "N. A."; } public string this[int index] { get { string tmp; if( index >= 0 && index <= size-1 ) { tmp = namelist[index]; } else { tmp = ""; } return ( tmp ); } set { if( index >= 0 && index <= size-1 ) { namelist[index] = value; } } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = "Zara"; names[1] = "Riz"; names[2] = "Nuha"; names[3] = "Asif"; names[4] = "Davinder"; names[5] = "Sunil"; names[6] = "Rubic"; for ( int i = 0; i < IndexedNames.size; i++ ) { Console.WriteLine(names[i]); } Console.ReadKey(); } } }
編譯並執行上述程式碼後,將產生以下結果:
Zara Riz Nuha Asif Davinder Sunil Rubic N. A. N. A. N. A.
過載索引器
索引器可以過載。索引器也可以宣告多個引數,並且每個引數可以是不同的型別。索引不必是整數。C#允許索引為其他型別,例如字串。
以下示例演示了過載索引器:
using System; namespace IndexerApplication { class IndexedNames { private string[] namelist = new string[size]; static public int size = 10; public IndexedNames() { for (int i = 0; i < size; i++) { namelist[i] = "N. A."; } } public string this[int index] { get { string tmp; if( index >= 0 && index <= size-1 ) { tmp = namelist[index]; } else { tmp = ""; } return ( tmp ); } set { if( index >= 0 && index <= size-1 ) { namelist[index] = value; } } } public int this[string name] { get { int index = 0; while(index < size) { if (namelist[index] == name) { return index; } index++; } return index; } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = "Zara"; names[1] = "Riz"; names[2] = "Nuha"; names[3] = "Asif"; names[4] = "Davinder"; names[5] = "Sunil"; names[6] = "Rubic"; //using the first indexer with int parameter for (int i = 0; i < IndexedNames.size; i++) { Console.WriteLine(names[i]); } //using the second indexer with the string parameter Console.WriteLine(names["Nuha"]); Console.ReadKey(); } } }
編譯並執行上述程式碼後,將產生以下結果:
Zara Riz Nuha Asif Davinder Sunil Rubic N. A. N. A. N. A. 2
廣告