C# 类(12)索引器


索引器 (indexer)

  索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。它可以使得像数组那样对对象使用下标。它提供了通过索引方式方便地访问类的数据信息的方法。
 
  要声明类或结构上的索引器,请使用this关键字,例如:
 
  public int this[int index] //声明索引器
 
  {
 
  // get and set 访问
 
  }
 
  索引器的修饰符有:new、public、protected、internal、private、virtual、sealed、override、abstract和extern。当索引器声明包含extern修饰符时,称该索引器为外部索引器。因为外部索引器声明不提供任何实际的实现,所以它的每个访问器声明都由一个分号组成。
 
  索引器的签名由其形参的数量和类型组成。它不包括索引器类型或形参名。如果在同一类中声明一个以上的索引器,则它们必须具有不同的签名。
 
  索引器值不归类为变量;因此,不能将索引器值作为ref或out参数来传递。
 
  索引必须是实例成员。
 
  下面用一个例子来说明如何声明和使用索引器。
 
  在本示例中,定义了一个泛型类,并为其提供了简单的get和set访问器方法(作为分配和检索值的方法)。Program 类为存储字符串创建了此类的一个实例。代码如下:
 
  class SampleCollection<T>
 
  {
 
  private T[] arr = new T[100];
 
  public T this[int i]
 
  {
 
  get { return arr[i]; }
 
  set { arr[i] = value; }
 
  }
 
  }
 
  下面是如何使用上述代码实现的索引器,具体代码示例如下:
 
  class Program
 
  {
 
  static void Main(string[] args)
 
  {
 
  SampleCollection <string> s = new SampleCollection<string>();
 
  s[0] = "索引器的使用";
 
  System.Console.WriteLine(s[0]);
 
  }
 
  }
 
  C#并不将索引类型限制为整数。例如,对索引器使用字符串可能是有用的。通过搜索集合内的字符串并返回相应的值,可以实现此类的索引器。如下所示:uing System;
 
  using System.Collections;
 
  class IndexClass
 
  {
 
  private Hashtable ht = new Hashtable();
 
  public object this[object key]
 
  {
 
  get { return ht[key]; }
 
  set { ht[key] = value); }
 
  }
 
  }
 
  由于访问器可被重载,字符串和整数版本可以共存。以上代码中的关键字value用来定义设置索引器分配的值,关键字this用于定义的索引器。



代码示例:

using
System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { // 使用索引器可以很方便的使用类中的数组或者集合. class MyClass { private float[] fs = new float[3] { 1.1f, 2.2f, 3.3f }; /* 属性 */ public int Length { get { return fs.Length; } set { fs = new float[value]; } } /* 索引器 */ public float this[int n] { get { return fs[n]; } set { fs[n] = value; } } } class Program { static void Main(string[] args) { MyClass My = new MyClass(); for (int i = 0; i < My.Length; i++) { My[i] = i; // 此时对象可以以数组的形式使用类中的数组. Console.WriteLine(My[i]); // 0 , 1 ,2 } } } }


posted @ 2012-10-02 21:10  梦断难寻  阅读(485)  评论(0编辑  收藏  举报