1、foreach循环的优点数组
C#支持foreach关键字,foreach在处理集合和数组相对于for存在如下几个优点:oop
一、foreach语句简洁this
二、效率比for要高(C#是强类型检查,for循环对于数组访问的时候,要对索引的有效值进行检查)spa
三、不用关心数组的起始索引是几(由于有不少开发者是从其余语言转到C#的,有些语言的起始索引多是1或者是0)code
四、处理多维数组(不包括锯齿数组)更加的方便,代码以下:blog
int[,] nVisited ={ {1,2,3}, {4,5,6}, {7,8,9} }; // Use "for" to loop two-dimension array(使用for循环二维数组) Console.WriteLine("User 'for' to loop two-dimension array"); for (int i = 0; i < nVisited.GetLength(0); i++) for (int j = 0; j < nVisited.GetLength(1); j++) Console.Write(nVisited[i, j]); Console.WriteLine(); //Use "foreach" to loop two-dimension array(使用foreach循环二维数组) Console.WriteLine("User 'foreach' to loop two-dimension array"); foreach (var item in nVisited) Console.Write(item.ToString());
foreach只用一行代码就将全部元素循环了出来,而for循环则就须要不少行代码才能够.索引
注:foreach处理锯齿数组需进行两次foreach循环资源
int[][] nVisited = new int[3][]; nVisited[0] = new int[3] { 1, 2, 3 }; nVisited[1] = new int[3] { 4, 5, 6 }; nVisited[2] = new int[6] { 1, 2, 3, 4, 5, 6 }; //Use "foreach" to loop two-dimension array(使用foreach循环二维数组) Console.WriteLine("User 'foreach' to loop two-dimension array"); foreach (var item in nVisited) foreach (var val in item) Console.WriteLine(val.ToString());
五、在类型转换方面foreach不用显示地进行类型转换开发
int[] val = { 1, 2, 3 }; ArrayList list = new ArrayList(); list.AddRange(val); foreach (int item in list)//在循环语句中指定当前正在循环的元素的类型,不须要进行拆箱转换 { Console.WriteLine((2*item)); } Console.WriteLine(); for (int i = 0; i < list.Count; i++) { int item = (int)list[i];//for循环须要进行拆箱 Console.WriteLine(2 * item); }
六、当集合元素如List<T>等在使用foreach进行循环时,每循环完一个元素,就会释放对应的资源,代码以下:it
using (IEnumerator<T> enumerator = collection.GetEnumerator()) { while (enumerator.MoveNext()) { this.Add(enumerator.Current); } }
2、foreach循环的劣势
一、上面说了foreach循环的时候会释放使用完的资源,因此会形成额外的gc开销,因此使用的时候,请酌情考虑
二、foreach也称为只读循环,因此再循环数组/集合的时候,没法对数组/集合进行修改。
三、数组中的每一项必须与其余的项类型相等.