例如我們曾經這樣的寫法: dgvList.Rows.Cells[“Stuno”] 、 dic[“key”] 等等,這種使用中括號來定位數據的時候就是索引器的使用。
01.C#中的類成員可以是任意類型,包括數組和集合。當一個類包含了數組和集合成員時,索引器將大大簡化對數組或集合成員的存取操作。
02.定義索引器的方式與定義屬性有些類似,其一般形式如下:
[修飾符] 數據類型 this[索引類型 index]
{
get{//獲得屬性的代碼}
set{ //設置屬性的代碼}
}
//在Student類中創建私有的數組 定義索引器來訪問和取值
public class Student
{
//該類中有一個字符串類型的數組
private string[] name=new string[2];
//定義一個索引器,給name數組賦值和取值
public string this[int index]
{
get { return name[index]; }
set { name[index] = value; }
}
}
//在方法中就可以進行調用了
static void Main(string[] args)
{
Student stu=new Student();
stu[0] = "張三";
stu[1] = "李四";
Console.WriteLine(stu[0]);
Console.ReadKey();
}
03.索引器的本質是類(看IL源碼得知)