Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...