usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacenettest{/** * The indexer is syntactically convenient for you to create a class, struct, or interface that the client application can access as an array. Indexers are often implemented in types that are primarily used to encapsulate internal collections or arrays. * Indexers allow instances of a class or struct to be indexed in the same way as an array, and indexers are similar to attributes, unlike indexers where access is a parameter. * Indexer and array comparison: * (1) indexer index value (index) type Unrestricted * (2) indexer allows overloading * (3) indexer is not a variable * Indexer and attribute different points * (1) attribute is identified by name, indexer is labeled as function Knowledge * (2) indexers can be overloaded, properties cannot * (3) Indexers cannot be declared static, properties can * indexer values do not belong to variables; Therefore, indexer values cannot be passed as ref or out parameters. * **/ Public classIndexclass {PrivateHashtable name =NewHashtable (); //1: Access values via key Public string This[intIndex] { Get{returnName[index]. ToString (); } Set{name. ADD (index, value); } } //2: Access key via Values Public int This[stringAName] { Get { //Hashtable is actually stored in the DictionaryEntry (dictionary) type, if you want to traverse a hashtable, you need to use the DictionaryEntry foreach(DictionaryEntry Dinchname) { if(d.value.tostring () = =aName) { returnConvert.ToInt32 (D.key); } } return-1; } Set{name. ADD (value, aName); } } } //Interface, index Public InterfaceISomeInterface {//Indexer declaration: int This[intIndex] { Get; Set; } } //implementing the interface. Public classIndexerclass:isomeinterface {Private int[] arr =New int[ -]; Public int This[intIndex//Indexer Declaration { Get { //The Arr object would throw IndexOutOfRange exception. returnArr[index]; } Set{Arr[index]=value; } } }}
Static voidMain (string[] args) { //use of the first type of indexerIndexclass Indexer =NewIndexclass (); indexer[1] ="Zhang San";//use of the set accessorindexer[2] ="John Doe"; Console.WriteLine ("the name is numbered 1:"+ indexer[1]);//use of Get accessorsConsole.WriteLine ("the name is numbered 2:"+ indexer[2]); Console.WriteLine (); //use of the second type of indexerConsole.WriteLine ("the number of the Zhang San is:"+ indexer["Zhang San"]);//use of Get accessorsConsole.WriteLine ("the number of the John Doe is:"+ indexer["John Doe"]); indexer["Harry"] =3;//use of the set accessorConsole.WriteLine ("the number of the Harry is:"+ indexer["Harry"]); Console.WriteLine (); Indexerclass Test=NewIndexerclass (); System.Random Rand=NewSystem.Random (); //Call the indexer-initialize its elements. for(inti =0; I <Ten; i++) {Test[i]=Rand. Next (); } for(inti =0; I <Ten; i++) {System.Console.WriteLine ("Element #{0} = {1}", I, test[i]); } console.readline (); }
Index in C #