What is the use of Indexers?

前端 未结 5 687
野性不改
野性不改 2020-12-16 06:15

What is the real use of indexer in C#?

It looks pretty confusing as I am a new c# programmer. It looks like an array of objects but it\'s not.

5条回答
  •  眼角桃花
    2020-12-16 06:50

    You can think of an indexer as a Property that takes a parameter. What you do with this parameter is up to you.

    Generally, the indexers are used where providing , well, an index to your object makes sense.

    For instance, if your object deals with collections of items, being able to access them using a simple '[]' syntax makes sense because it's simple to think of it as an array to which we give the position of the object we want to return.

    I wrote a blog entry a while ago on the aspects of indexers using reflection.
    One of the examples I gave was:

     using System;  
     using System.Collections;  
    
     public class DayPlanner  
     {  
         // We store our indexer values in here   
         Hashtable _meetings = new System.Collections.Hashtable();  
    
         // First indexer  
         public string this[DateTime date] {  
             get {  
                 return _meetings[date] as string;  
             }  
             set {  
                 _meetings[date] = value;  
             }  
         }  
    
         // Second indexer, overloads the first  
         public string this[string datestr] {  
             get {  
                 return this[DateTime.Parse(datestr)] as string;   
             }  
             set {  
                 this[DateTime.Parse(datestr)] = value;  
             }  
         }  
     }  
    

    And then you could use it like this:

      DayPlanner myDay = new DayPlanner();  
      myDay[DateTime.Parse("2006/02/03")] = "Lunch";  
      ...  
      string whatNow = myDay["2006/06/26"];
    

    That's just to show you can twist the purpose of an indexer to do what you want.
    Doesn't mean you should though... :-)

提交回复
热议问题