c# 为什么要使用Array、ArrayList、List?
c#也是一直在进化的,从数组进化到ArrayList,再进化到泛型就是个例子。
static void Main(string[] args) { //数组的增删改查 //定义数组 int[] Numbers = new int[5] { 1,2,3,4,5 }; Console.WriteLine("原数组为:"); StringBuilder sb = new StringBuilder(); foreach (var item in Numbers) { sb.Append(item+","); } Console.WriteLine(sb.ToString()); Console.WriteLine("现在在0位置插入9"); Add(Numbers, 0, 9); Console.WriteLine("现在在1位置插入9"); Add(Numbers, 1, 9); Console.WriteLine("现在在2位置插入9"); Add(Numbers, 2, 9); Console.WriteLine("现在在3位置插入9"); Add(Numbers, 3, 9); Console.WriteLine("现在在4位置插入9"); Add(Numbers, 4, 9); Console.WriteLine("现在在5位置插入9"); Add(Numbers, 5, 9); Console.WriteLine("数组不能动态改变,所以用ArrayList"); ArrayList arrayInt = new ArrayList(); for (int i = 0; i < 5; i++) { arrayInt.Add(i+1); } Console.WriteLine("现在在ArrayList中的3位置增加9"); arrayInt.Insert(3,9); StringBuilder sbArray = new StringBuilder(); foreach (var item in arrayInt) { sbArray.Append(item+","); } Console.WriteLine(sbArray.ToString()); Console.WriteLine("因为ArrayList中都转换为object,有性能消耗,因此微软引入了泛型"); List<int> listInt = new List<int>(); for (int i = 0; i < 5; i++) { listInt.Add(i+1); } Console.WriteLine("现在在List中的3位置增加9"); listInt.Insert(3,9); StringBuilder sbList = new StringBuilder(); foreach (var item in listInt) { sbList.Append(item + ","); } Console.WriteLine(sbList.ToString()); Console.ReadKey(); } /// <summary> /// 数组的添加 /// </summary> /// <param name="numbers">原始数组</param> /// <param name="i">要添加的位置从0开始</param> /// <param name="k">要添加的值</param> public static void Add(int[] numbers,int i,int k) { if (i<0&&i>numbers.Length) { Console.WriteLine($"要插入的位置只能0到{numbers.Length}之间"); }else { //因为数组定义就不能更改,所以必须把原数组拷贝到新数组中 int[] newArray = new int[numbers.Length+1]; int m = 0; for (int j = 0; j < numbers.Length; j++) { if (j!=i) { //添加到新数组中 newArray[m] = numbers[j]; m++; } else if(j==i) { newArray[j] = k; newArray[j+1]= numbers[j]; m = j + 2; } } //如果要插入的位置就是原数组的最大长度+1,则直接赋值 if (i == numbers.Length) { newArray[i] = k; } StringBuilder sb = new StringBuilder(); foreach (var item in newArray) { sb.Append(item+","); } Console.WriteLine(sb.ToString()); } }