An indexer (Indexer) is a new class member introduced by C # that makes an object in a class as easy and intuitive to reference as an array. Indexers are very similar to properties, but indexers can have parameter lists and only work on instance objects, not directly on classes. A class that defines an indexer allows you to access members of a class using the [] operator, just as you would access an array. (There are, of course, many advanced applications, such as the ability to map arrays through indexers, etc.)
This article simply demonstrates the concept of an indexer and the basic way to use it:
Look at the code, here is the definition of the class, with an indexer definition in the middle
definition of Class Public classPerson {//define two fields of information Private stringname; Private stringpassword; //define a Name property to manipulate the name field Public stringName {Set{name =value;} Get{returnname;} } //define a Password property to manipulate the Password field Public stringPassword {Set{Password =value;} Get{returnpassword;} } //defines the indexer, the Name field has an index value of 0, and the index value of the password field is 1 Public string This[intIndex] { Get { if(Index = =0)returnname; Else if(Index = =1)returnpassword; Else return NULL; } Set { if(Index = =0) name =value; Else if(Index = =1) Password =value; } } }
Here's how to use indexers:
Indexer Useprotected voidPage_Load (Objectsender, EventArgs e) { //declare and instantiate this classPerson p =NewPerson (); //using indexers to assign values to two properties of a classp[0] ="Jarod"; p[1] ="123456,./"; //use class properties to get two field informationLabel1.Text = P.name +" / "+P.password; }
Very simply, in the class above we mapped the name field of the class to the index value of 0, and the password field map has an index value of 1. With this mapping, you can assign a value to the class name and password in the following ways.
p[0"jarod"; // Set Name field value p[1"123456,./"; // Setting the Password field value
The use of indexers in C # classes two