C#中的索引器原理

朋友们,还记得我们在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(中间语言)是(属性的格式):

这就是索引器。

猜你喜欢

转载自www.linuxidc.com/Linux/2016-04/130274.htm