索引器(Indexer) 允许一个对象可以像数组一样使用下标的方式来访问。
当您为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。您可以使用数组访问运算符 [ ] 来访问该类的的成员。
class Indexer
{
private string[] nameList = new string[] { "Mary" };
public string this[int idx]
{
get
{
if (idx >= 0 && idx < nameList.Length)
return nameList[idx];
else
return string.Empty;
}
set
{
if (idx >= 0 && idx < nameList.Length)
nameList[idx]= value;
}
}
引用: