索引器允许类或结构的实例就想数组一样进行索引。
this关键字定义索引。不必根据整数值进行索引,由开发者自己决定特定的查找机制。
索引器可被重载,可以有多个参数。
索引器用法举例1:
class MyArrayList
    {
        object[] objarr = new object[0];
 public MyArrayList(int Cap)      //构造函数
        {
            objarr = new object[Cap];
        }
 public object this[int i]       //定义索引
        {
            get
            {
                return objarr[i];
            }
            set
            {
                objarr[i] = value;
            }
        }
    }
class Program
    {
        static void Main(string[] args)
        {
     MyArrayList mal = new MyArrayList(1);//定义长度为1的数组
           
            mal[0]="aaa";                        //赋值给索引为0的实例
            Console.WriteLine(mal[0]);  //读取索引为0的实例的值
        }
输出结果为: aaa
本例中,可以看出索引器类似于属性,可以直接通过索引存取实例的值。
举例2:
class Myclass
        {
         string[] Days =new string[7]
{"Mon","Tue","Wen","Thurs","Fri","Sat","Sun"};
         private int GetDay(string testDay)
            {
              int i = 0;
              foreach (string day in Days)      //定义查找机制,遍历数组,返回查
                {                               //找对象的序列号
                     if (day == testDay)
                        {
                            return i;
                        }
                        i++;
                }
              return -1;
           }
         public int this[string day]         //定义只读索引器,get方法调用GetDay
         {                                                   //方法,查找对象
             get
             {
                 return (GetDay(day));
             }
         }
        }
class Program
    {
        static void Main(string[] args)
        {
     Myclass week = new Myclass();
            System.Console.WriteLine(week["Fri"]);
            System.Console.WriteLine(week["Made-up Day"]);
           
        }
    }
结果为: 4       -1
本例中,由开发者自己定义查找机制。通过索引器,返回字符串在实例中的索引序号。
有更多的用法,欢迎留言交流。