When a class contains arrays or set members, you can use the indexer to greatly simplify access to arrays or set members.
The usage is as follows:
[Modifier] Data TypeThis[Index]
{
Get{//Obtain the attributeCode}
Set{//Code for setting attributes}
}
//Modifiers include public, protected, Private, internal, new, virtual, sealed, override, abstract, and extern.
//The data type is the type of the array or set element to be accessed.
For example, the following is a class where the indexer is used:
Public Class Myclass {
Public String Name { Get ; Set ;}
Public Int Age { Get ; Set ;}
Public String [] Arr = New String [ 10 ];
// Outside the class, you can use myclass [Param] to access the value of the string array arr [Param] In myclass.
Public String This [ Int Param] {
Get { Return Arr [Param];}
Set {Arr [Param] = value ;}
}
}
The following describes how to store a string to the 0th elements of the array member ARR in the class through the indexer:
//Accessing myclass [Index] is equivalent to accessing the array arr [Index] In myclass.
Myclass =NewMyclass ();
Myclass [0] ="Johnsmith";
Console. writeline (myclass. Arr [0]);
For more information, see index in C #.