索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class indextest
{
private string[] name = new string[6];
public string this[int index] //定义索引,用this表示该对象
{
get { return name[index]; }
set { name[index] = value; }
}
}
class maintest
{
public static void Main()
{
indextest student = new indextest();
for (int i = 0; i < 6; i++)
student[i] = Console.ReadLine(); //调用set访问器
Console.WriteLine("-----------");
for (int i = 0; i < 6; i++)
Console.WriteLine(student[i]); //调用get访问器
Console.ReadLine();
}
}