String in C # is the ability to access the characters in an object through an indexer, but cannot modify the value of a character.
Let's look at the definition of indexers in string, such as.
The indexer, like a property, has a Get method, but does not have a set method, so this is why a variable of type string in C # is read-only.
Now let's write our own indexer:
1 class Program2 {3 Static voidMain (string[] args)4 {5Test test =NewTest ();6Console.WriteLine ("Test[1] = {0},test[2] = {1}", test[1],test[2]);7 8test[1] ="Cai Anchor";9test[2] ="Shi Jin Ai";TenConsole.WriteLine ("Test[1] = {0},test[2] = {1}", test[1], test[2]); One AConsole.WriteLine ("overloading of indexers:"+ test["Winchang",5]); - } - } the - Public classTest - { - Private stringName1 ="Chen Xinhong"; + Private stringName2 ="Liu Guanhuo"; - + Public string This[intIndex] A { at Get - { - if(Index = =1) - { - returnname1; - } in Else if(Index = =2) - { to returnname2; + } - Else the { * Throw NewException ("the value of the index is out of range"); $ }Panax Notoginseng } - Set the { + if(Index = =1) A { theName1 =value; + } - Else if(Index = =2) $ { $Name2 =value; - } - Else the { - Throw NewException ("the value of the index is out of range");Wuyi } the } - } Wu //indexers can also be overloaded. - Public string This[stringStrintx] About { $ Get - { - returnSTR +x; - } A } +}
Output Result:
As we see, indexers have get and set methods like properties, and can be overloaded like functions in a class.
In the ADO technology, indexers are frequently used frequently.
Object-oriented basis-indexer