索引器的作用:令对象可像数组一般被索引
索引器
internal class TestClass
{public int[] arr = { 1, 2, 3, 4, 5 };public string this[int index] // 前者为返回类型,后者为索引类型// 返回类型代表get函数的返回值类型、set函数的value类型(等价于代表赋值时的数据类型){get{if (index >= 0 && index < arr.Length) return arr[index].ToString();else return "NaN";}set{if (index >= 0 && index < arr.Length) arr[index] = int.Parse(value);}}
}
测试
internal class Program
{private static void Main(string[] args){TestClass testClass = new();testClass[0] = "10";testClass[1] = "20";testClass[2] = "30";testClass[3] = "40";testClass[4] = "50";Console.WriteLine(testClass[0]);Console.WriteLine(testClass[1]);Console.WriteLine(testClass[2]);Console.WriteLine(testClass[3]);Console.WriteLine(testClass[4]);}
}
结果