索引器有什么用? [英] What is the use of Indexers?
问题描述
C#中索引器的真正用途是什么?
What is the real use of indexer in C#?
当我是一名新的C#程序员时,这看起来非常令人困惑.它看起来像一个对象数组,但不是.
It looks pretty confusing as I am a new c# programmer. It looks like an array of objects but it's not.
推荐答案
您可以将索引器视为带有参数的属性.该参数由您决定.
You can think of an indexer as a Property that takes a parameter. What you do with this parameter is up to you.
通常,在为对象提供 index 有意义的地方使用索引器.
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... :-)
这篇关于索引器有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!