An in-depth understanding of the indexer and an in-depth understanding of the Index
In our development, there are many common places where the indexer is used. The indexer is a very subtle member of a special class, which allows the object to be accessed in an array-like way, when a class contains arrays and set members, the indexer greatly simplifies access to arrays or set members. Make the program look more intuitive and easier to write.
I. Define the Indexer
The way to define the indexer is similar to the way to define attributes. The general form is as follows:
[Modifier] data type this [index type index]
{
Get {// code for obtaining attributes}
Set {// set the Property Code}
}
Modifiers includePublic, protected, private, internal, new, virtual, sealed, override, abstract, extern.
The data type is the type of the array or set element to be accessed.
The indexer type indicates which type of index the indexer uses to access arrays or set elements. It can be an integer or a string. this indicates operating the array or set members of this object, you can simply understand it as the name of the indexer. Therefore, the indexer cannot have a user-defined name.
II. The essence of the indexer is Class
3. Example of creating an index
Public class Person {// first defines an array private string [] str = new string [2]; // Add the indexer public string this [int index] {get {return str [index] ;}set {str [index] = value ;}}}
Call in the Main method
Person person = new Person (); // assign the person [0] = "Zhang San"; person [1] = "Li Si"; Console by means of the index. writeLine (person [0]); Console. writeLine (erson [1]); Console. readKey ();