C# foreach循環較for循環的優勢與劣勢


一、foreach循環的優勢

C#支持foreach關鍵字,foreach在處理集合和數組相對於for存在以下幾個優勢:

1、foreach語句簡潔

2、效率比for要高(C#是強類型檢查,for循環對於數組訪問的時候,要對索引的有效值進行檢查)

3、不用關心數組的起始索引是幾(因為有很多開發者是從其他語言轉到C#的,有些語言的起始索引可能是1或者是0)

4、處理多維數組(不包括鋸齒數組)更加的方便,代碼如下:

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());

5、在類型轉換方面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);
}

6、當集合元素如List<T>等在使用foreach進行循環時,每循環完一個元素,就會釋放對應的資源,代碼如下:

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

 

二、foreach循環的劣勢

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

2、foreach也稱為只讀循環,所以再循環數組/集合的時候,無法對數組/集合進行修改。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM