索引器(Indexer)

索引器(Indexer) 容许一个对象能够像数组一样应用下标的形式来拜访。

当您为类定义一个索引器时,该类的行为就会像一个 虚构数组(virtual array) 一样。您能够应用数组拜访运算符 [ ] 来拜访该类的的成员。

语法

一维索引器的语法如下:

element-type this[int index]{   // get 拜访器   get   {      // 返回 index 指定的值   }   // set 拜访器   set   {      // 设置 index 指定的值   }}

索引器(Indexer)的用处

索引器的行为的申明在某种程度上相似于属性(property)。就像属性(property),您可应用 get 和 set 拜访器来定义索引器。然而,属性返回或设置一个特定的数据成员,而索引器返回或设置对象实例的一个特定值。换句话说,它把实例数据分为更小的局部,并索引每个局部,获取或设置每个局部。

定义一个属性(property)包含提供属性名称。索引器定义的时候不带有名称,但带有 this 关键字,它指向对象实例。上面的实例演示了这个概念:

实例

using System;namespace IndexerApplication{   class IndexedNames   {      private string[] namelist = new string[size];      static public int size = 10;      public IndexedNames()      {         for (int i = 0; i < size; i++)         namelist[i] = "N. A.";      }      public string this[int index]      {         get         {            string tmp;            if( index >= 0 && index <= size-1 )            {               tmp = namelist[index];            }            else            {               tmp = "";            }            return ( tmp );         }         set         {            if( index >= 0 && index <= size-1 )            {               namelist[index] = value;            }         }      }      static void Main(string[] args)      {         IndexedNames names = new IndexedNames();         names[0] = "Zara";         names[1] = "Riz";         names[2] = "Nuha";         names[3] = "Asif";         names[4] = "Davinder";         names[5] = "Sunil";         names[6] = "Rubic";         for ( int i = 0; i < IndexedNames.size; i++ )         {            Console.WriteLine(names[i]);         }         Console.ReadKey();      }   }}

当下面的代码被编译和执行时,它会产生下列后果:

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.