C#_索引器
当我们访问数组中的某个数据时 通过索引访问
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };//[] 索引器 5索引Console.WriteLine(arr[5]);
类也可以使用索引器 类中定义的有索引器
internal class Class1
{public int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
}
static void Main(string[] args)
{Class1 c1 = new Class1();Console.WriteLine(c1.arr[5]); // 常规访问某个类中某个数组的某个数据
}
定义索引器
1、使用属性索引指定数组 this[int index]
internal class Class1{public int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };//定义索引器public int this[int index]{get{return arr[index];}set{arr[index] = value;}}}
static void Main(string[] args)
{//通过类中定义的索引器 操作类中的某个数组//修改值nc1[5] = 1000;//获取值Console.WriteLine(c1[5]);
}
2、使用属性 索引指定字段 this[string a]
internal class Class1
{public string name;public string age;public string this[string a] // "name"{get{if (a == "name"){return this.name;}else if (a == "age"){return this.age;}return "";}set{if (a == "name"){this.name = value;}else if (a == "age"){this.age = value;}}}
}
static void Main(string[] args)
{Class1 c2 = new Class1();c2.name = "张三";c2.age = "18";Console.WriteLine(c2["name"]);
}