Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

c# - What is the use of Indexers?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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... :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...