c#中索引器允许一个对象像数组一样使用下标的方式来访问 当你为类定义一个索引器的时候,该类的行为就会像一个虚拟数组一样 你可以使用数组访问运算符**[]**来访问类的成员
一维数组的语法如下
element-type this[int index] { // get 访问器 get { // 返回 index 指定的值 } // set 访问器 set { // 设置 index 指定的值 } }索引器的行为的声明在某种程度上类似于类中的属性 可以使用get和set方法来定义索引器 但是 属性返回或设置的特定数据成员,而索引器返回或设置对象实例的一个特定的值 定义一个属性包括属性名称,索引器定义的时候不带有名称,但是带有this关键字 它指向对象实例
实例
using System; namespace IndexerApplication { class testIndexer{ static public int size = 10; private string[] namelist = new string[size]; public testIndexer() { for(int i = 0; i < size; i++) { namelist[i] = "null"; } } public string this[int index] { get { string tmp; if (index >= 0 && index < size) { tmp = namelist[index]; } else { tmp = "null"; } return tmp; } set { if (index >= 0 && index < size) { namelist[index] = value; } } } public int this[string name] { get { int index = 0; while (index >= 0) { if (namelist[index] == name) { return index; } index++; } return index; } } static void Main(string[] args) { testIndexer names = new testIndexer(); names[0] = "zhang"; names[1] = "zi"; names[2] = "shuai"; Console.WriteLine("输出所有names中的元素"); for(int i = 0; i < testIndexer.size; i++) { Console.WriteLine(names[i]); } Console.Write("输出names中内容为zhang的元素索引:"); Console.WriteLine(names["zhang"]); Console.ReadKey(); } } }运行结果: 可以看到我们可以像使用数组一样的使用我们的类,其中我们自己根据需要创建对应类型
c#索引器就介绍这么多,希望我所写的对大家有帮助