朋友們,還記得我們在C#語言開發中用到過索引器嗎?
記得在獲得DataGridView控件的某列值時:dgvlist.SelectedRows[0].Cells[0].Value;
記得在獲得ListView控件的某列值時:listView1.SelectedItems[0].SubItems[0].Text;
記得在讀取數據庫記錄給變量賦值時:result=dr["StudentName"].ToString();
記得Dictionary中根據key值來獲取Value值時:dic["key"]等等
我們只知道索引器給我們解決了許多問題,帶來了許多方便,但你知道它的原理所在嗎?
01.C#中的類成員可以是任意類型,包括數組和集合。當一個類包含了數組和集合成員時,索引器將大大簡化對數組或集合成員的存取操作。
02.定義索引器的方式與定義屬性有些類似,其一般形式如下:
[修飾符] 數據類型 this[索引類型 index]
{
get{//獲得屬性的代碼}
set{ //設置屬性的代碼}
}
03.索引器的本質是屬性
下面我們以一個例子來了解索引器的用法和原理:
01.創建一個Test類,裡面定義一個數組和一個索引器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 索引器
{
public class Test
{
//01.首先定義一個數組
private string[] name=new string[2];
//02.根據創建索引器的語法定義一個索引器,給name數組賦值和取值
public string this[int index]
{
get { return name[index]; }
set { name[index] = value; }
}
}
}
02.在Main方法中通過索引器給Test類中的數組賦值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 索引器
{
class Program
{
static void Main(string[] args)
{
//01.首先你得實例化Test類的對象
Test test=new Test();
//02.利用索引器給Test類中的數組賦值
test[0] = "張總";
test[1] = "吳總";
//03.打印查看效果
for (int i = 0; i < 2; i++)
{
Console.WriteLine(test[i]);
}
Console.ReadLine();
}
}
}
03.效果如下:

這樣就是索引器的應用
上面說到
索引器的本質是屬性
是的,我們可以發現上面定義索引器的代碼的IL(中間語言)是(屬性的格式):

這就是索引器