欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C#教程

當(dāng)前位置:主頁 > 軟件編程 > C#教程 >

C#中foreach循環(huán)對比for循環(huán)的優(yōu)勢和劣勢

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C#教程|點擊: 次

前言

循環(huán)語句為眾多程序員們提供了很大的便利,有while、do...while、for和 foreach。而且foreach語句很簡潔,但是它的優(yōu)點不僅僅在于此,它的效率也是最高的。本文將詳細(xì)給大家關(guān)于C#中foreach循環(huán)對比for循環(huán)的優(yōu)勢和劣勢,下面話不多說了,來一起看看詳細(xì)的介紹吧。

一、foreach循環(huán)的優(yōu)勢

C#支持foreach關(guān)鍵字,foreach在處理集合和數(shù)組相對于for存在以下幾個優(yōu)勢:

1、foreach語句簡潔

2、效率比for要高(C#是強類型檢查,for循環(huán)對于數(shù)組訪問的時候,要對索引的有效值進(jìn)行檢查)

3、不用關(guān)心數(shù)組的起始索引是幾(因為有很多開發(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)時,每循環(huán)完一個元素,就會釋放對應(yīng)的資源,代碼如下:

using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
  while (enumerator.MoveNext())
  {
   this.Add(enumerator.Current);
  }
}

二、foreach循環(huán)的劣勢

1、上面說了foreach循環(huán)的時候會釋放使用完的資源,所以會造成額外的gc開銷,所以使用的時候,請酌情考慮

2、foreach也稱為只讀循環(huán),所以再循環(huán)數(shù)組/集合的時候,無法對數(shù)組/集合進(jìn)行修改。

3、數(shù)組中的每一項必須與其他的項類型相等.

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對我們的支持。

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有