您可以将索引器视为带参数的Property.您对此参数的处理取决于您自己.
通常,索引器用于提供对象的索引是有意义的.
例如,如果您的对象处理项目集合,则能够使用简单'[]'语法访问它们是有意义的,因为很容易将其视为一个数组,我们给出了要返回的对象的位置.
我不久前写了一篇关于使用反射的索引器方面的博客文章.
我给出的一个例子是:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
DayPlanner myDay = new DayPlanner();
myDay[DateTime.Parse("2006/02/03")] = "Lunch";
...
string whatNow = myDay["2006/06/26"];
Run Code Online (Sandbox Code Playgroud)
这只是为了表明你可以扭曲索引器的目的来做你想要的.
并不意味着你应该...... :-)
| 归档时间: |
|
| 查看次数: |
1974 次 |
| 最近记录: |