C#中的数组类型[],List,Array,ArrayList的区别
以遇见了 数组[],List,Array,ArrayList,这些,总是不知道其区别,经过一番查找学习后终于知道了。在此还要感谢千一网络。我是在那里面看见的,经过实际后,我打算记录下来,再次感谢千一网络。
现将整个实验代码放下在下面:
CompareArray.cs
using System; using System.Collections; using System.Collections.Generic; namespace SampleList { class CompareArray { public static void CompareContainer() { //[] 的命名空间 System.Int32 int[] arr = new int[] { 1, 2, 3 }; PrintArrayInfo(arr, "[]最初数值"); ChangeArray(arr); PrintArrayInfo(arr, "[]改变后值"); Console.WriteLine("\n"); // List 的命名空间是 System.Collections.Generic List<int> list = new List<int>() { 1, 2, 3 }; PrintArrayInfo(list, "List最初数值"); ChangeArray(list); PrintArrayInfo(list, "List改变后值"); Console.WriteLine("\n"); // Array 的命名空间是 System . Array 是抽象类,不能使用 new Array 创建 Array array = Array.CreateInstance(System.Type.GetType("System.Int32"), 3); array.SetValue(1, 0); array.SetValue(2, 1); array.SetValue(3, 2); PrintArrayInfo(array, "Array最初数值"); ChangeArray(array); PrintArrayInfo(array, "Array改变后值"); Console.WriteLine("\n"); // ArrayList 的命名空间是 System.Collections ArrayList arrayList = new ArrayList(); arrayList.Add(1); arrayList.Add(2); arrayList.Add(3); PrintArrayInfo(arrayList, "ArrayList最初数值"); ChangeArray(arrayList); PrintArrayInfo(arrayList, "ArrayList改变后值"); Console.Read(); } //改变其[]类型值 static void ChangeArray(int[] arr) { for (int index = 0; index < arr.Length; index++) { arr[index] *= 2; } } //输出数字值 static void PrintArrayInfo(int[] arr, string str) { Console.Write(str + ":"); foreach (int index in arr) { Console.Write("\t" + index); } Console.WriteLine(); } //改变其List类型值 static void ChangeArray(List<int> list) { for (int index = 0; index < list.Count; index++) { list[index] *= 2; } } //输出数字值 static void PrintArrayInfo(List<int> list, string str) { Console.Write(str + ":"); foreach (int index in list) { Console.Write("\t" + index); } Console.WriteLine(); } //改变其Array类型值 static void ChangeArray(Array array) { for (int index = 0; index < array.Length; index++) { int cahngevalue = (int)array.GetValue(index) * 2; array.SetValue(cahngevalue, index); } } //输出数字值 static void PrintArrayInfo(Array array, string str) { Console.Write(str + ":"); for (int index = 0; index < array.Length; index++) { Console.Write("\t" + (int)array.GetValue(index)); } Console.WriteLine(); } //改变其ArrayList类型值 static void ChangeArray(ArrayList arrayList) { for (int index = 0; index < arrayList.Count; index++) { arrayList[index] = (int)arrayList[index] * 2; } } //输出数字值 static void PrintArrayInfo(ArrayList arrayList, string str) { Console.Write(str + ":"); for (int index = 0; index < arrayList.Count; index++) { Console.Write("\t" + arrayList[index]); } Console.WriteLine(); } } }
[] 是针对特定类型、固定长度的。
List 是针对特定类型、任意长度的。
Array 是针对任意类型、固定长度的。
ArrayList 是针对任意类型、任意长度的。
注: Array 和 ArrayList 是通过存储 object 实现任意类型的,所以使用时要转换。
运行结果如下:
如需转载,还望表明出处,谢谢......

浙公网安备 33010602011771号