首页 > 开发 > 综合 > 正文

Using Indexers in C#

2024-07-21 02:22:11
字体:
来源:转载
供稿:网友
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
31:          {
32:              if( index >= 0 && index <= size-1 )
33:                words[index] = value;
34:          }
35:      }
36:  }
37:  
38:  public class testapp
39:  {
40:     public static void main()
41:     {
42:        spellinglist mylist = new spellinglist();
43:  
44:        mylist[3] = "=====";
45:        mylist[4] = "brad";
46:        mylist[5] = "was";
47:        mylist[6] = "here!";
48:        mylist[7] = "=====";
49:  
50:        for ( int x = 0; x < spellinglist.size; x++ )
51:            console.writeline(mylist[x]);
52:     }
53:  }

the output from this listing is:

word0
word1
word2
=====
brad
was
here!
=====
word8
word9

this listing creates an indexer to be used with the spellinglist class. the spellinglist class contains an array of strings called words that can be used to store a list of words. this list is set to the size of the variable declared in line 9.

lines 11 to 15 contain a constructor for spellinglist that sets initial values into each element of the array. you could just as easily have requested the words from the reader or read them from a file. this constructor assigns the string value word## to each of the elements in the array, where ## is the element number of the array.

jumping down to the testapp class in lines 38 to 53, you see how the spellinglist class is going to be used. in line 42, the spellinglist class is used to instantiate the mylist object that will hold the words. line 42 also causes the constructor to be executed. this initializes the word## values. lines 44 to 48 then change some of these values.

if you think back to how you worked with arrays, you should be saying, "wait a minute" as you look at lines 44 to 48. to access the value of one of the words, you would normally have to access the data member within the object. when using arrays as a data member, you learned that you would assign a value to the fourth element as

mylist.words[3] = "=====";

line 44, however, is accessing the fourth element within the object, which has been set to be the fourth element in the words array.

an indexer has been created for the spellinglist class in lines 17 to 35. this indexer enables you to access the elements within the words array using just the object name.

line 17 is the defining line for the indexer. you know this is an indexer rather than a property because the this keyword is used instead of a name. additionally, this is given an index (called index). the indexer will return a string value.

lines 19 to 29 contain the get portion of the indexer. the get block returns a value based on the index. in this class, this value is an element from the words array. you can return any value you want. the value should, however, make sense. in line 23, a check is done to make sure the index value is valid. if you don't check the value of the index, you risk having an exception thrown. in this listing, if the index is out of the range, a null value is returned (line 26). if the index is valid, the value stored in the words array at the index location will be returned.

the set portion of the indexer is in lines 30 to 34. this block can be used to set information within the object. as with properties, the value keyword contains the value being assigned. in this code, the index value is again checked to make sure it is valid. if it is, a word in the words array will be updated at the index location with the value assigned.

looking again at the test class, you see that the set indexer block is used to assign values in lines 44 to 48. for line 44, the set indexer block will be called with value equal to ===== and will be passed with an index value of 3. in line 45, value will be brad and the index is 4. in line 51, the get indexer block is called with an index value of x. the value returned will be the string value returned by the get indexer block.

there are times to use indexers and there are times to not use them. you should use indexers when it makes your code more readable and easier to understand. for example, you can create a stack that can have items placed on it and taken off of it. using an indexer, you could access items within the stack without needing to remove items.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表