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

后端 未结 11 2032
暖寄归人
暖寄归人 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: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.

提交回复
热议问题