You can think of an indexer as a Property that takes a parameter.
What you do with this parameter is up to you.
Generally, the indexers are used where providing , well, an index to your object makes sense.
For instance, if your object deals with collections of items, being able to access them using a simple '[]'
syntax makes sense because it's simple to think of it as an array to which we give the position of the object we want to return.
I wrote a blog entry a while ago on the aspects of indexers using reflection.
One of the examples I gave was:
using System;
using System.Collections;
public class DayPlanner
{
// We store our indexer values in here
Hashtable _meetings = new System.Collections.Hashtable();
// First indexer
public string this[DateTime date] {
get {
return _meetings[date] as string;
}
set {
_meetings[date] = value;
}
}
// Second indexer, overloads the first
public string this[string datestr] {
get {
return this[DateTime.Parse(datestr)] as string;
}
set {
this[DateTime.Parse(datestr)] = value;
}
}
}
And then you could use it like this:
DayPlanner myDay = new DayPlanner();
myDay[DateTime.Parse("2006/02/03")] = "Lunch";
...
string whatNow = myDay["2006/06/26"];
That's just to show you can twist the purpose of an indexer to do what you want.
Doesn't mean you should though... :-)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…