概念
索引器(Indexer) 允許類中的對象可以像數組那樣方便、直觀的被引用。當為類定義一個索引器時,該類的行為就會像一個 虛擬數組(virtual array) 一樣。
索引器可以有參數列表,且只能作用在實例對象上,而不能在類上直接作用。
可以使用數組訪問運算符([ ])來訪問該類的實例。
索引器的行為的聲明在某種程度上類似於屬性(property)。屬性可使用 get 和 set 訪問器來定義索引器。但是屬性返回或設置的是一個特定的數據成員,而索引器返回或設置對象實例的一個特定值。
定義一個一維數組的索引器:
element-type this[int index] { // get 訪問器 get { // 返回 index 指定的值 } // set 訪問器 set { // 設置 index 指定的值 } }
提示:索引器必須以this關鍵字定義,this 是類實例化之后的對象
實例:
using System; namespace C_Pro { public class Student { private string name; private string grade; public string Name { get {return name; } set {name = value; } } public string Grade { get {return grade; } set {grade = value; } } // 定義索引器 public string this[int index] { get { if (index == 0) return name; else if (index == 1) return grade; else return null; } set { if (index == 0) name = value; else if (index == 1) grade = value; } } static void Main(string[] args) { Student s = new Student(); s[0] = "Jeson"; s[1] = "First-year"; Console.WriteLine(s.Name); Console.WriteLine(s.Grade); Console.ReadKey(); } } }
運行后結果:
Jeson First-year
重載索引器
索引器(Indexer)可被重載。索引器聲明的時候也可帶有多個參數,且每個參數可以是不同的類型。沒有必要讓索引器必須是整型的。C# 允許索引器可以是其他類型,例如,字符串類型。
using System; namespace C_Pro { public class IndexedNames { private string[] namelist = {"a", "b", "c", "d"}; // 輸入namelist的index返回對應的值 public string this[int index] { get { return namelist[index]; } set { namelist[index] = value; } } // 輸入namelist的值,返回對應的索引 public int this[string name] { get { for (int i=0; i<namelist.Length; i++) { if (namelist[i] == name) return i; } return -1; } } static void Main(string[] args) { IndexedNames name = new IndexedNames(); Console.WriteLine(name[1]); Console.WriteLine(name["a"]); } } }
運行后結果:
b 0
索引器與數組的區別:
- 索引器的索引值(Index)類型不限定為整數,用來訪問數組的索引值(Index)一定為整數,而索引器的索引值類型可以定義為其他類型。
- 索引器允許重載, 一個類不限定為只能定義一個索引器,只要索引器的函數簽名不同,就可以定義多個索引器,可以重載它的功能。
- 索引器不是一個變量,索引器沒有直接定義數據存儲的地方,而數組有。索引器具有Get和Set訪問器。
索引器與屬性的區別:
- 索引器以函數簽名方式 this 來標識,而屬性采用名稱來標識,名稱可以任意。
- 索引器可以重載,而屬性不能重載。
- 索引器不能用static 來進行聲明,而屬性可以。索引器永遠屬於實例成員,因此不能聲明為static。