Real world use cases for C# indexers?

后端 未结 14 1524
时光说笑
时光说笑 2020-12-04 15:26

I\'ve seen lot of examples for c# Indexers, but in what way will it help me in real life situations.

I know the C# guru wouldn\'t have added this if it wasn\'t a ser

14条回答
  •  天涯浪人
    2020-12-04 16:04

    Addition to @code-kings post.

    Moreover, calling RollNumberVariable[0] will trigger the behavior of the default collection's indexer. While indexers are actually properties, it's on your behalf to write your own logic when extracting data. You can easily delegate most of index-parameter value to the internal collection but you can also return any arbitrary value for certain index values.

    Just an example - you can have 2+ internal collections in different format, but the external user will interact with them trough a single indexer (which will kinda work as a dispatcher), while those collection will be hidden. This pretty much encourages the encapsulation principle.

提交回复
热议问题