The use of indexers in asp.net is analyzed in this paper. Share to everyone for your reference. Specifically as follows:
An indexer definition is similar to a property, but its functionality is not the same as that of a property. Indexers provide a special way to write get and set accessors. Properties can access the object's data as if it were a field, and indexers can access class members as if they were accessing the array.
First, indexer characteristics
1, get accessor return value. The set accessor assigns a value.
2, this keyword is used to define indexers.
3, the value keyword is used to define values that are assigned by the set indexer.
4. Indexers do not have to be indexed based on integer values, and you decide how to define a specific lookup mechanism.
5, indexers can be overloaded.
6. Indexers can have multiple formal parameters, such as when accessing two-dimensional arrays.
7. Indexers enable objects to be indexed in a way similar to arrays.
the way to define an indexer is similar to defining a property, and its general form is as follows:
Copy Code code as follows:
[modifier] Data type this[indexed type index]
{
get{//the code that gets the property}
set{//Set Property Code}
}
As with methods, indexers have 5 access protection levels new, public, protected, internal, private, and 4 inheritance behaviors that modify virtual, sealed, override, abstract, and external indexers. There is no difference between these behaviors and methods. The only difference is that indexers cannot be static (static), which is easy to understand in the semantics of object references. It is noteworthy that when overriding (override) implements indexers, you should use Base[e to access indexers of the parent class.
Iii. Indexer code example
The C # code is as follows:
Copy Code code as follows:
Class samplecollection<t>
{
Private t[] arr = new t[100];
Public T This[int I]
{
Get
{
return arr[i];
}
Set
{
Arr[i] = value;
}
}
}
Class Program
{
static void Main (string[] args)
{
samplecollection<string> stringcollection = new samplecollection<string> ();
Stringcollection[0] = "Hello, world";
System.Console.WriteLine (Stringcollection[0]);
}
}
Four, the definition indexer should pay attention to the following content:
1, all indexers Use this keyword to replace the method name. Class or struct only allows an indexer to be defined and is always named this.
2. Indexers allow instances of classes or structs to be indexed in the same way as arrays. Indexers are similar to properties, except that their accessors take parameters.
3. Indexers are not necessarily indexed according to an integer value, you can specify the parameter type according to your programming requirements.
I hope this article will help you with the C # program.