To put it simply, the so-called indexer is a special type of attributes. With these attributes, You can reference your own classes as you reference arrays.
The declaration method is as follows (similar to the attribute ):
// Modifier type name this [type name parameter name]
Public type this [int Index]
{
Get
{
//...
}
Set
{
//...
}
}
Simple Example:
Using system. collections;Static void main (string [] ARGs)
{
// Call the intbits. intbits method to assign 63 to bits
Intbits bits = new intbits (63 );
// Obtain the bool value of index 6. In this case, BITs [6] Will call get in "Public bool this [int Index]" and the value is true.
Bool peek = bits [6];
Console. writeline ("bits [6] value: {0}", peek );
Bits [0] = true;
Console. writeline (); Console. readkey ();
} Struct intbits
{
Private int bits;
Public intbits (INT initialbitvalue)
{
Bits = initialbitvalue;
Console. writeline (BITs );
}
// Define the Indexer
// The attribute name of the index is this, which indicates the current instance of the reference class. The parameter list is included in square brackets rather than brackets.
Public bool this [int Index]
{
Get
{
Return true;
}
Set
{
If (value)
{
Bits = 100;
}
}
} Note: All indexers use the this keyword to replace the method name. Class or struct can only define one indexer and is always named this. The indexer allows instances of classes or structures to be indexed in the same way as arrays. The indexer is similar to an attribute, but its accessors use parameters. Get accessors return values. Set accessors allocation value. This keyword is used to define the indexer. The value keyword is used to define the value allocated by the set indexer. The indexer does not need to index based on the integer value. It is up to you to decide how to define a specific search mechanism. The indexer can be overloaded. The indexer can have multiple parameters, for example, when accessing a two-dimensional array. The indexer can use a hundred-value subscript, while the array can only use an integer Subscript: for example, the following defines a string Index
Public int this [string name] {...} Attribute and Indexer There are some differences between attributes and indexer: Each attribute of the class must have a unique name, and each indexer defined in the class must have a unique signature) or the parameter list (so that the indexer can be reloaded ). The attribute can be static, but the indexer must be an instance Member. The parameters that can be accessed and passed to the indexer by the access function defined for the indexer, while the attribute access function has no parameters. |