The indexer in C#(C#中的索引器)

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

In the following example, a generic class is defined and provided with simple get and set accessor methods as a means of assigning and retrieving values. The Program class creates an instance of this class for storing strings.

Sample using indexer

 

Indexers Overview

  1. Indexers enable objects to be indexed in a similar manner to arrays.

  2. A get accessor returns a value. A set accessor assigns a value.

  3. The this keyword is used to define the indexers.

  4. The value keyword is used to define the value being assigned by the set indexer.

  5. Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

  6. Indexers can be overloaded.

  7. Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array. Below is simple example:

Indexer taking two arguments

 

Addition

  1. Just like any other class members, indexers can also participate in inheritance. A base class indexer is inherited to the derived class.

  2. A Base class indexer can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level.

  3. An indexer inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract indexer in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors.

  If the abstract class contains only set accessor, we can implement only set in the derived class.

 

Go to my home for more posts

posted on 2009-10-29 00:27  lantionzy  阅读(337)  评论(0编辑  收藏  举报