- 声明索引类似于声明属性,只有get访问器与set访问器。
- 索引没有名称,在名称的位置是关键字this。
- 参数列表在方括号中间,并且参数列表中至少必须声明一个参数。
- 如果需要创建多个实例对象,可以考虑使用索引。
class Employee { public string LastName; public string FirstName; public string SecondName; public string this[int index] //索引声明 { get //get访问器 { switch (index) { case 0: return LastName; case 1: return FirstName; case 2: return SecondName; default: throw new ArgumentOutOfRangeException(); } } set //set访问器 { switch (index) { case 0: LastName = value; break; case 1: FirstName = value; break; case 2: SecondName = value; break; } } } }
class Program { static void Main(string[] args) { Employee emp = new Employee(); emp[0] = "Doe"; emp[1] = "Jane"; emp[2] = "Dallas"; Console.WriteLine("{0}",emp[0]); Console.WriteLine("{0}", emp[1]); Console.WriteLine("{0}", emp[2]); Console.ReadKey(); } }
输出结果为:Doe
Jane
Dallas