索引器(Indexer)是C#引入的一个新型的类成员,它使得对象可以像数组那样被方便,直观的引用。索引器非常类似于我们前面讲到的属性,但索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用 。
C# 允许将某些对象视为一维或多维数组。实际上,c#允许在对象后面紧跟【】运算符。该运算符可以接受一个或多个任意类型的参数(整数,字符串,任何类的对象。。。。)。这些参数用逗号隔开。
类的索引器可以看为特殊的属性,索引器的两个访问器之一是可选的,但至少要有一个访问器。索引器的参数不能用ref或者out关键字修饰。
public
class
Persons
{
// 存放名字的数组
string [] m_Names;
// 构造函数初始化m_Names数组
public Persons( params string [] names)
{
m_Names = new string [names.Length];
// 将名字复制入数组
names.CopyTo(m_Names, 0 );
}
// 根据姓名返回索引
public int this [ string name]
{
get
{
return Array.IndexOf(m_Names, name);
}
}
public string this [ int index]
{
// 根据索引返回姓名
get
{
return m_Names[index];
}
set
{
m_Names[index] = value;
}
}
}
class Program
{
static void Main( string [] args)
{
Persons person = new Persons( " Mike " , " Kobe " , " Tim " , " Allen " );
Console.WriteLine(person[ 1 ]);
int index = person[ " Kobe " ];
person[index] = " Shaqe " ;
Console.WriteLine(person[index]);
}
}
{
// 存放名字的数组
string [] m_Names;
// 构造函数初始化m_Names数组
public Persons( params string [] names)
{
m_Names = new string [names.Length];
// 将名字复制入数组
names.CopyTo(m_Names, 0 );
}
// 根据姓名返回索引
public int this [ string name]
{
get
{
return Array.IndexOf(m_Names, name);
}
}
public string this [ int index]
{
// 根据索引返回姓名
get
{
return m_Names[index];
}
set
{
m_Names[index] = value;
}
}
}
class Program
{
static void Main( string [] args)
{
Persons person = new Persons( " Mike " , " Kobe " , " Tim " , " Allen " );
Console.WriteLine(person[ 1 ]);
int index = person[ " Kobe " ];
person[index] = " Shaqe " ;
Console.WriteLine(person[index]);
}
}
通常,实现了索引的类必须支持使用foreach和in关键字来访问的功能