C# what is the point or benefit of an indexer?

后端 未结 11 2089
暖寄归人
暖寄归人 2020-12-16 16:07

Doing some code reading and stumbled upon this snippet that I haven\'t seen before:

public SomeClass {
  public someInterface this[String strParameter] {
            


        
相关标签:
11条回答
  • 2020-12-16 16:30

    The "this" keyword is an indexer

    from http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx

    "Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters."

    0 讨论(0)
  • 2020-12-16 16:31

    It's an operator overload. Useful if you are writing a collection class for example where it would make sense to access it using array notation, e.g. collection[someIndex].

    You could of course write a collection.GetElement(someIndex) function equivalent, but it's a style/readability thing.

    0 讨论(0)
  • 2020-12-16 16:38

    Well you could use this method in a key-value pair class.

    I am not sure what the analogous class is in c#, but in c++ STL, there is the map class where you call the method with the SomeObject["key"] and it will return the "value" associated with that key.

    0 讨论(0)
  • 2020-12-16 16:40

    It allows you to do associative array lookups (a.k.a. "dictionary style"), just as you mentioned in your question.

    And that's the whole point. Some people like that, particularly people coming from languages that have it built in, like Python or PHP

    0 讨论(0)
  • 2020-12-16 16:41

    It seems like a lot of the answers are focusing on what an indexer is, not why you would want to use one.

    As far as I'm concerned, here is the motivation to use an indexer:

    You are working on a class that has a collection of some sort, but you want the class to appear to users (consumers of the class) as if it is a collection.

    The best example I can think of is the DataRow class in ADO.NET. If you want to get the value of the fifth cell of a DataRow, you can either use DataRow.Item[4] or DataRow[4]. The latter form is a convenient and logical shortcut, and it shows off pretty nicely why you'd want to use an indexer. To the user, the DataRow can be thought of as just a collection of cells (even though it is really more than that), so it makes sense to be able to get and set cell values directly, without having to remember that you are actually getting/setting an Item.

    Hope that helps.

    0 讨论(0)
提交回复
热议问题