日期:2014-05-18 浏览次数:20884 次
C# Array和ArrayList区别 收藏
一,C# array数组的用法范例:
type[]?? typename=new type[size];?
如int[] a=new int[2];string[] str=new string[5];
实事上我们平常是用int[],string[]...的,此时我们已经创建一个Array数组,只不过我们平常没有这种意识而已.
(1):type数据类型不能缺;且要统一,而不能是如 int[] a=new Array[];
(2):数组的大小size不能缺,否则c#认为是出错的,因为数组是一段固定长度的内存;
(3):右边是一个中括号[],而不是()
实例:
??????????? //Array ar = new Array();//错误,无法创建抽象类或接口“System.Array”的实例
??????????? //int[] array = new Array[3];错误,
??????????? //int[] array = new Array[];错误,必须指定数组的大小或初始值
??????????? //int[] array = new Array[3];//错误,无法转换为int[]
??????????? //int[] array=new int[];//错误,必须指定数组的大小或初始值
??????????? //平常我们int[],string[]...事实上就是声明一个array数组了
??????????? int[] array = new int[5];
??????????? //或int[] arr={1,2,3};
??????????? for (int i = 0; i < 5; i++)
??????????? {
??????????????? array[i] = i*100;//注:array数组并不提供add,clear,addRange..方法,而是直接设置或获取值
??????????????? Response.Write(array[i] + "<br>");
??????????? }
??????????? Response.Write(array.Length + "<br><br>");
?
或
?int [] intarray=new int[9];
???? intarray[0]=10;
???? intarray[1]=20;
???? intarray[2]=30;
???? intarray[3]=40;
???? intarray[4]=50;
???? intarray[5]=60;
???? intarray[6]=70;
???? intarray[7]=80;
???? intarray[8]=90;
?
二,C# ArrayList数组的用法范例:
?ArrayList al = new ArrayList();
??????????? for (int i = 0; i < 3; i++)
??????????? {
??????????????? al.Add(i);
??????????????? Response.Write(al[i].ToString() + "<br>");//输出数组中的元素值
??????????????? // Response.Write(al[i]+ "<br>");
??????????? }
??????????? Response.Write(al.Count + "<br><br>");
??????????? foreach (int obj in al)//或foreach (object obj in al),因为al是一个object类型的数组
??????????? {
??????????????? Response.Write(obj+"-OK"+"<br>");
??????????? }
三,ArrayList和Array相互之间的转化
???????? (1)以下是把ArrayList数组中的值拷贝到Array中去的实例用法
????????? //int[] IResult=new int[al.Count];
??????????? //al.CopyTo(IResult);
??????????? //或是用下面的方法
????????? int[] IResult = (int[])al.ToArray(typeof(Int32));//ToArray(Int32);这样错误,一定要强制类型转换
????????? //Person[] personArrayFromList = (Person[])personList.ToArray(typeof(Person));??
???????? foreach(int item?? in IResult)
??????????? {
????????????? Response.Write(item.ToString());
??????????? }
?
Response.Write("以下是把Array数组中的值拷贝到ArrayList中去的实例用法" + "<br>" + "结果为:<br>");
??????????? int[] a ={ 222, 333, 555 };
??????????? ArrayList arrList = new ArrayList();
??????????? foreach (object obj in a)//或foreach (int obj in a)
??????????? {
??????????????? arrList.Add(obj);
??????????????? Response.Write(obj+"<br>");
??????????? }
<script type="text/javascript"></script>