詳細描述C#索引器
簡單說來,所謂C#索引器就是一類特殊的屬性,通過它們你就可以像引用數(shù)組一樣引用自己的類。聲明方法如下(與屬性相似):
- public type this [int index]
- {
- get
- {
- //...
- }
- set
- {
- //...
- }
- }
用例子簡單說明:
- using System.Collections;
- static void Main(string[] args)
- {
- //調(diào)用IntBits.IntBits方法,意為將63賦給bits
- IntBits bits = new IntBits(63);
- //獲得索引6的bool值,此時 bits[6]將調(diào)用索引器"public bool this[int index]"中的Get,值為True
- bool peek = bits[6];
- Console.WriteLine("bits[6] Value: {0}",peek);
- bits[0] = true;
- Console.WriteLine();
- Console.ReadKey();
- }
- struct IntBits
- {
- private int bits;
- public IntBits(int initialBitValue)
- {
- bits = initialBitValue;
- Console.WriteLine(bits);
- }
- //定義索引器
- //索引器的“屬性名”是this,意思是回引類的當(dāng)前實例,參數(shù)列表包含在方括號而非括號之內(nèi)。
- public bool this [int index]
- {
- get
- {
- return true;
- }
- set
- {
- if (value)
- {
- bits = 100;
- }
- }
- }
備注:
所有C#索引器都使用this關(guān)鍵詞來取代方法名。Class或Struct只允許定義一個索引器,而且總是命名為this。
索引器允許類或結(jié)構(gòu)的實例按照與數(shù)組相同的方式進行索引。索引器類似于屬性,不同之處在于它們的訪問器采用參數(shù)。
◆get 訪問器返回值。set 訪問器分配值。
◆this 關(guān)鍵字用于定義索引器。
◆value 關(guān)鍵字用于定義由 set 索引器分配的值。
索引器不必根據(jù)整數(shù)值進行索引,由您決定如何定義特定的查找機制。索引器可被重載。 索引器可以有多個形參,例如當(dāng)訪問二維數(shù)組時。索引器可以使用百數(shù)值下標(biāo),而數(shù)組只能使用整數(shù)下標(biāo):如下列定義一個String下標(biāo)的索引器
- public int this [string name] {...}
屬性和索引器
屬性和索引器之間有好些差別:
類的每一個屬性都必須擁有***的名稱,而類里定義的每一個C#索引器都必須擁有***的簽名(signature)或者參數(shù)列表(這樣就可以實現(xiàn)索引器重載)。 屬性可以是static(靜態(tài)的)而索引器則必須是實例成員。 為C#索引器定義的訪問函數(shù)可以訪問傳遞給索引器的參數(shù),而屬性訪問函數(shù)則沒有參數(shù)。
【編輯推薦】