int[] nArray=new int[100]; //use "foreach"to loop array foreach(int i in nArray) Debug.WriteLine(i.ToString()); //use "for"to loop array for(int i=0;i<nArray.Length;i++) Debug.WriteLine(nArray[i].ToString()); //Another way using "for" to loop array int nLength=nArray.Length for(int i=0;i<nLength;i++) Debug.WriteLine(nArray[i].ToString());
foreach语句很简洁,它的效率也是最高的,上述第三种方式是效率最低的,虽然表面上不用每次访问引用类型的属性,但是由于C#是强类型检查,对于数组访问的时候,要对索引的有效值进行判断,即第三种方式相当于如下
// Another way using "for" to loop array int nLength = nArray.Length; for( int i = 0; i < nLength; i++ ) { if(i<nArray.Length) Debug.WriteLine(nArray[i].ToString()); else throw new IndexOutOfRangeException(); }
int[,] nVisited=new int[8,8]; //use "for" to loop two-dimension array for(int i=0;i<nVisited.GetLength(0);i++) for(int j=0;j<nVisited.GetLength(1);j++) Debug.WriteLine(nVisited[i,j].ToString()); //use "foreach" to loop two-dimension array foreach(int i in nVisited) Debug.WriteLine(i.ToString());
// Init an arraylist object int[] nArray=new int[100]; ArrayList arrInt=new ArrayList(); arrInt.AddRange(nArray); //use "foreach" to loop an arraylist foreach(int i in arrInt) Debug.WriteLine(i.ToString()); //use "for" to loop an arraylist for(int i=0;i<arrInt.Count;i++) { int n=(int)arrInt[i]; Debug.WriteLine(n.ToString()); }
// Use "foreach" to loop an arraylist foreach( int i in arrInt ) { i++;//Can't be compiled Debug.WriteLine( i.ToString() ); } // Use "foreach" to loop an arraylist foreach( int i in arrInt ) { arrInt.Remove( i );//It will generate error in run-time Debug.WriteLine( i.ToString() ); }
// Use "for" to loop an arraylist for(int i=arrInt.Count-1;i>=0;i--) { int n=(int) arrInt[i]; if(n==5) arrInt.RemoveAt(i);//Remove data here Debug.WriteLine(n.ToString()); }