List<int> list = new List<int>(20); public int this[int index] { get { if (index < 0) { index = 0; } if (index > 19) { index = 19; } return list[index]; } set { if (index < 0) { index = 0; } if (index > 19) { index = 19; } list[index] = value;//value就是赋值的数据 } }
索引器使用前,那个集合必须先要初始化了
就是使用Add方法添加元素,不能通过索引赋值的方式添加元素