Real world use cases for C# indexers?

后端 未结 14 1520
时光说笑
时光说笑 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:07

    The most obvious examples, as mentioned by Skurmedel, are List and Dictionary. What would you prefer over:

    List list = new List { "a", "b", "c" };
    string value = list[1]; // This is using an indexer
    
    Dictionary dictionary = new Dictionary
    {
        { "foo", "bar" },
        { "x", "y" }
    };
    string value = dictionary["x"]; // This is using an indexer
    

    ? Now it may be relatively rare for you need to write an indexer (usually when you're creating a collection-like class), but I suspect you use them reasonably frequently.

提交回复
热议问题