When should you use C# indexers?

后端 未结 10 1577
终归单人心
终归单人心 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:29

    I remember there was this time when I had a long inside a class, and some digits of that particular long meant something (for example if the third digit was a 3 it meant that the chart had a specific type of encoding, horrible system I know but I didn't invent it)

    So I did something like this to return the xth digit of the number:

    protected int this[int index]
    {
        get
        {
            int tempN = Number;
            if (index > 0)
            {
                tempN /= index * 10;
            }
            return tempN % 10;
        }
    }
    

    It was protected because a different method used it, so it was kind of a helper. Of course a simple GetDigit(int a) would've been the same thing (and more self-explanatory) but at the time I thought it was one of the few times I thought using an indexer would make sense. Haven't used them since =(.

提交回复
热议问题