C# - Indexer at its meaningful application
I understand indexer enable us to access a collection within a class as though the class itself were an array.
Suppose we are developing a project开发者_开发知识库 ,where do we fit the real pratical usage (example may help) of such indexers ?
Look to almost any of the collection classes in the framework for an example. If I were to retrieve an item from a hashtable in a language without an indexer, I would use syntax like:
object o = table.getvalue(key);
where an indexer allows somewhat simpler syntax:
object o = table[key];
(purposely ignoring typing/generics issues in the samples above)
You have several examples in the generic collections of the framework itself. Dictionary is a pretty good example:
Dictionary<string, User> Users;
Users["Jorge"].ResetPassword();
That would be much elegant and simple than
Users.GetElementByKey("Jorge").ResetPassword();
indexer enables us to access a collection within a class as though the class itself were an array.
While that is true, you can write a class that does not have a permanent collection of items within itself, but still be capable to dynamically provide you with a calculated value when indexed. The data may be collected in real-time from the Internet, or any other data source - I imagine, as an example a class SearchResults
, that I could use to obtain Google search results for a string like this: Console.out.WriteLine(SearchResults["Stackoverflow"].count)
. It gathers the data only when I'm asking for it and return a collection of the retrieved items.
Suppose you are developing Microsoft .NET Framework for other developers to use (which is really a "real-world project"). You need to write a class that acts like an array but supports getting resized dynamically (the List<T>
class). Without an indexer, you could write two methods to get and set elements:
public T get(int index) { ... }
public void set(int index, T value) { ... }
// (Java advocates: no offense intended)
Assume a user of your library wants to increment the second element. She'll have to write:
list.set(1, list.get(1) + 1);
With an indexer, the syntax is much simpler, more readable, and easier to understand:
list[1]++;
(similar arguments apply to things like Dictionary<TKey,TValue>
...)
Well, the obvious application for using indexers are ... (surprise) Collections.
Such as:
Lists:
list[4]
Hash tables:
table["foo"] table[Color.Black]
Remember that indexers aren't restricted to integer arguments.
If the collection is sorted, then the first and last elements may be useful for getting a minimum or maximum element.
In ASP.Net, there are several objects that use indexers like Application, Session, and Request.
精彩评论