Original address: Https://msdn.microsoft.com/zh-cn/library/6x16t2tx (vs.80). aspx
Indexers allow instances of a class or struct to be indexed in the same way as an array. Indexers are similar to properties, except that their accessors take parameters.
In the following example, a generic class is defined and a simple get and set accessor method (as a method of assigning and retrieving values) is provided. The program class creates an instance of this class for the storage string.
C#
Class samplecollection<t>{ private t[] arr = new t[100]; Public T This[int i] { get { return arr[i]; } Set { Arr[i] = value;}} } This class shows how client code uses the Indexerclass program{ static void Main (string[] args) { Sample collection<string> stringcollection = new samplecollection<string> (); Stringcollection[0] = "Hello, world"; System.Console.WriteLine (Stringcollection[0]);} }
Indexer Overview
Indexers enable an object to be indexed in a similar way to an array.
The get accessor returns a value. The set accessor assigns a value.
The This keyword is used to define indexers.
The value keyword is used to define the values assigned by the set indexer.
Indexers do not have to be indexed by integer values, and you decide how to define a specific lookup mechanism.
Indexers can be overloaded.
Indexers can have multiple parameters, such as when accessing a two-dimensional array.
related chapters
Using Indexers (C # Programming Guide)
Indexers in Interfaces (C # Programming Guide)
Comparisons between properties and indexers (C # Programming Guide)
Asymmetric accessor Accessibility (C # Programming Guide)
Indexer Sample
Index Properties sample
Indexers (C # Programming Guide)