1. 何为索引器
索引器(Indexer)是C#引入的一个新型的类成员,它使得类的对象可以像数组一样,使用下标访问,方便直观。索引器的功能类似于属性,它具有get和set方法,可以用来控制类中的数组、集合类成员。
2. 如何使用
2.1 定义
访问修饰符 class 类名
{
访问修饰符 返回值的数据类型 this[索引值的数据类型 标识符]
{
get { 获得数据的代码; }
set { 设置数据的代码; }
}
}
2.2 实例
public class Student //学生类
{
public string Name { get; set; }
public int Age { get; set; }
const int MAX = 3;
private string[] SchoolName = new string[MAX]; //学校名称数组
//索引器运用
public string this[int index]
{
get
{
if (index >= 0 && index < MAX)
return SchoolName[index];
else
throw new ArgumentOutOfRangeException();
}
set
{
if (index >= 0 && index < MAX)
SchoolName[index] = value;
else
throw new ArgumentOutOfRangeException();
}
}
}
//访问索引器
static void Main(string[] args)
{
Student student1 = new Student();
student1.Name = "小明";
student1.Age = 20;
//赋值
student1[0] = "希望小学";
student1[1] = "希望中学";
student1[2] = "希望一中";
//取值
Console.WriteLine("就读学校:{0},{1},{2}", student1[0], student1[1], student1[2]);
}
索引器访问用对象名[]访问。当然,首先这个类你需要先定义索引器的访问方法public string this[int index]{}。参数列表可以是任意的数据结构,所以访问起来可以按照程序员自己的意愿,简化了代码,对类内数据的操作更加得方便。
也可以通过名字获取学校名。
public string this[string name]
{
get
{
for (int i = 0; i < MAX; i++)
{
if (name == SchoolName[i])
{
return SchoolName[i];
}
}
return null;
}
set
{
}
}