As you can see, indexers are yet another
form of syntactic sugar, given that this functionality
can also be achieved using “normal” public methods such as AddPerson() or GetPerson(). Neverthe-
less, when you support indexer methods on your custom collection types, they integrate well into
the fabric of the .NET base class libraries.
While building indexer methods is quite commonplace when you are building custom collec-
tions, do remember that generic types give you this very functionality out of the box. Consider the
following method, which makes use of a generic List of Person objects. Note we are able to sim-
ply use the indexer of List directly, for example:
static void UseGenericListOfPeople()
{
List
myPeople = new List
();
myPeople.Add(new Person("Lisa", "Simpson", 9));
myPeople.Add(new Person("Bart", "Simpson", 7));
Do'stlaringiz bilan baham: