C# foreach循环较for循环的优势与劣势
一、foreach循環(huán)的優(yōu)勢
C#支持foreach關(guān)鍵字,foreach在處理集合和數(shù)組相對于for存在以下幾個(gè)優(yōu)勢:
1、foreach語句簡潔
2、效率比for要高(C#是強(qiáng)類型檢查,for循環(huán)對于數(shù)組訪問的時(shí)候,要對索引的有效值進(jìn)行檢查)
3、不用關(guān)心數(shù)組的起始索引是幾(因?yàn)橛泻芏嚅_發(fā)者是從其他語言轉(zhuǎn)到C#的,有些語言的起始索引可能是1或者是0)
4、處理多維數(shù)組(不包括鋸齒數(shù)組)更加的方便,代碼如下:
int[,] nVisited ={{1,2,3},{4,5,6},{7,8,9} }; // Use "for" to loop two-dimension array(使用for循環(huán)二維數(shù)組) 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循環(huán)二維數(shù)組) Console.WriteLine("User 'foreach' to loop two-dimension array"); foreach (var item in nVisited) Console.Write(item.ToString());foreach只用一行代碼就將所有元素循環(huán)了出來,而for循環(huán)則就需要很多行代碼才可以.
注:foreach處理鋸齒數(shù)組需進(jìn)行兩次foreach循環(huán)
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循環(huán)二維數(shù)組) Console.WriteLine("User 'foreach' to loop two-dimension array"); foreach (var item in nVisited)foreach (var val in item)Console.WriteLine(val.ToString());5、在類型轉(zhuǎn)換方面foreach不用顯示地進(jìn)行類型轉(zhuǎn)換
int[] val = { 1, 2, 3 }; ArrayList list = new ArrayList(); list.AddRange(val); foreach (int item in list)//在循環(huán)語句中指定當(dāng)前正在循環(huán)的元素的類型,不需要進(jìn)行拆箱轉(zhuǎn)換 { Console.WriteLine((2*item)); } Console.WriteLine(); for (int i = 0; i < list.Count; i++) { int item = (int)list[i];//for循環(huán)需要進(jìn)行拆箱 Console.WriteLine(2 * item); }6、當(dāng)集合元素如List<T>等在使用foreach進(jìn)行循環(huán)時(shí),每循環(huán)完一個(gè)元素,就會釋放對應(yīng)的資源,代碼如下:
using (IEnumerator<T> enumerator = collection.GetEnumerator()) {while (enumerator.MoveNext()){this.Add(enumerator.Current);} }?
二、foreach循環(huán)的劣勢
1、上面說了foreach循環(huán)的時(shí)候會釋放使用完的資源,所以會造成額外的gc開銷,所以使用的時(shí)候,請酌情考慮
2、foreach也稱為只讀循環(huán),所以再循環(huán)數(shù)組/集合的時(shí)候,無法對數(shù)組/集合進(jìn)行修改。
3、數(shù)組中的每一項(xiàng)必須與其他的項(xiàng)類型相等.
?
轉(zhuǎn)載于:https://www.cnblogs.com/GreenLeaves/p/7401605.html
總結(jié)
以上是生活随笔為你收集整理的C# foreach循环较for循环的优势与劣势的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 上传图片动态预览(兼容主流浏览器)
- 下一篇: WebApi 的CRUD 的方法的应用