When should you use C# indexers?

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

    Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

    Indexers enable objects to be indexed in a similar manner to arrays.

        // C#: INDEXER 
    using System; 
    using System.Collections; 
    
    class MyClass 
    { 
        private string []data = new string[5]; 
        public string this [int index] 
        { 
           get 
           { 
               return data[index]; 
           } 
           set 
           { 
               data[index] = value; 
           } 
        } 
    }
    
    class MyClient 
    { 
       public static void Main() 
       { 
          MyClass mc = new MyClass(); 
          mc[0] = "Rajesh"; 
          mc[1] = "A3-126"; 
          mc[2] = "Snehadara"; 
          mc[3] = "Irla"; 
          mc[4] = "Mumbai"; 
          Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc[1],mc[2],mc[3],mc[4]); 
       } 
    } 
    

    Code project

提交回复
热议问题