Indexers Overview
--------------------------------------------------------------------------------
Indexers enable objects to be indexed in a similar way to arrays.
A get accessor returns a value. A set accessor assigns a value.
The this keyword is used to define the indexers.
The value keyword is used to define the value being assigned by the set indexer.
Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.
Indexers can be overloaded.
Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.
class IndexerClass
{
private int[] arr = new int[100];
public int this[int index] // indexer declaration
{
get
{
// Check the index limits.
if (index < 0 || index >= 100)
{
return 0;
}
else
{
return arr[index];
}
}
set
{
if (!(index < 0 || index >= 100))
{
arr[index] = value;
}
}
}
}
class MainClass
{
static void Main()
{
IndexerClass test = new IndexerClass();
// Call the indexer to initialize the elements #2 and #5.
test[2] = 4;
test[5] = 32;
for (int i = 0; i <= 10; i++) { System.Console.WriteLine("Element #{0} = {1}", i, test[i]); } } } Output
--------------------------------------------------------------------------------
Element #0 = 0
Element #1 = 0
Element #2 = 4
Element #3 = 0
Element #4 = 0
Element #5 = 32
Element #6 = 0
Element #7 = 0
Element #8 = 0
Element #9 = 0
Element #10 = 0
Property | Indexer |
---|---|
Allows methods to be called as though they were public data members. | Allows methods on an object to be called as though the object is an array. |
Accessed through a simple name. | Accessed through an index. |
Can be a static or an instance member. | Must be an instance member. |
A get accessor of a property has no parameters. | A get accessor of an indexer has the same formal parameter list as the indexer. |
A set accessor of a property contains the implicit value parameter. | A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter. |
No comments:
Post a Comment