public void main() { //可以存储任何类型的数组 ArrayList alist = new ArrayList(); AddData(alist); RemoveData(alist); UpdateData(alist); SearchData(alist); OtherFun(alist); } /// <summary> /// 往集合加数据 /// </summary> /// <param name="alist"></param> public void AddData(ArrayList alist) { alist.Add(0); alist.Add(1.1); alist.Add("test"); alist.Add(true); alist.Add(new int[] { 1, 2 }); //增加一个数组,增加了1个 //批量添加 alist.AddRange(new int[] { 1, 2 });//匹配增加一个数据,增加了2个 alist.AddRange(new List<string>() { "test1", "test2" }); alist.Insert(1, "test3"); } /// <summary> /// 移除集合数据 /// </summary> /// <param name="alist"></param> public void RemoveData(ArrayList alist) { //移除: alist.Remove(0); alist.RemoveAt(1); alist.RemoveRange(1, 2); } /// <summary> /// 修改集合数据 /// </summary> /// <param name="alist"></param> public void UpdateData(ArrayList alist) { //修改 alist[0] = 4; alist.SetRange(0, new string[] { "a", "b" }); //for里面可以修改数据 for (int i = 0; i < alist.Count; i++) { alist[i] = 4; } //查询:foreach里面,不运行修改、删除、增加集合 foreach (object val in alist) { alist[0] = 1; //System.InvalidOperationException:“集合已修改;可能无法执行枚举操作。” } } /// <summary> /// 查询集合数据 /// </summary> /// <param name="alist"></param> public void SearchData(ArrayList alist) { for (int i = 0; i < alist.Count; i++) { } foreach (object val in alist) { } //通过枚举器、迭代器遍历,foreach的底层就是枚举器,也不能里面修改集合 IEnumerator ie = alist.GetEnumerator(); //一开始ie没有指向,需要movenext才开始指向第一位 while (ie.MoveNext()) { var val = ie.Current; } } /// <summary> /// 集合ArrayList的其他方法 /// </summary> /// <param name="alist"></param> public void OtherFun(ArrayList alist) { //排序 alist.Sort(); //顺序排序 alist.Reverse(); //倒叙排序 //拷贝 object[] obj = new object[10]; alist.CopyTo(obj); }