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

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也稱爲只讀循環,因此再循環數組/集合的時候,沒法對數組/集合進行修改。

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

相關文章
相關標籤/搜索