When should you use C# indexers?

后端 未结 10 1620
终归单人心
终归单人心 2020-12-06 10:10

I\'d like to use indexers more, but I\'m not sure when to use them. All I\'ve found online are examples that use classes like MyClass and IndexerClass

10条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 10:43

    Random order access

    You would use an enumerator if your data is normally accessed sequentially.

    An indexer on the other hand is useful for directly accessing a specific element, no specific order.

    This of course assumes you know the index of the element you want. Comboboxes for example have always supported two values: the string shown to the user, and the id that belongs with it. You could use the id from a selected item in a combobox to directly access the index of your collection, instead of having to search the collection.

    The nice thing about indexers in C# is that you can overload them, so you can access items through different kind of keys.

提交回复
热议问题