日期:2012-07-30  浏览次数:20429 次

An indexer enables you to use an index on an object to obtain values stored within the object. In essence this enables you to treat an object like an array.

An indexer is also similar to a property. As with properties, you use get and set when defining an indexer. Unlike properties, you are not obtaining a specific data member; rather, you are obtaining a value from the object itself. When you define a property, you define a property name. With indexers, instead of creating a name as you do with properties, you use the this keyword, which refers to the object instance and thus the object name is used. The format for defining an indexer is

public dataType this[int index]
{
    get
    {
         // Do whatever you want...
         return aValue;
    }
    set
    {
         // Do whatever you want
         // Generally you should set a value within the class
         // based on the index and the value they assign.
    }
}    

Creating an indexer enables you to use bracket notation ([]) with an object to set and get a value from an object. As you can see in the format shown earlier, you state the dataType that will be set and returned by the indexer. In the get section, you return a value that is of dataType. In the set block, you will be able to something with a value of dataType. As with properties and member functions, you can use the value keyword. This is the value passed as the argument to the set routine. Listing 1 presents a simple example of using an indexer.

Listing 1. Using an Indexer

1:  //  indx2.cs - Using an indexer
2:  //--------------------------------------------------
3:  
4:  using System;
5:  
6:  public class SpellingList
7:  {
8:      protected string[] words = new string[size];
9:      static public int size = 10;
10:  
11:      public SpellingList()
12:      {
13:          for (int x = 0; x < size; x++ )
14:              words[x] = String.Format("Word{0}", x);
15:      }
16:  
17:      public string this[int index]
18:      {
19:          get
20:          {
21:              string tmp;
22:  
23:              if( index >= 0 && index <= size-1 )
24:                 tmp = words[index];
25:              else
26:                 tmp = "";
27:  
28:              return ( tmp );
29:          }
30:          set<