软件编程
位置:首页>> 软件编程>> C#编程>> C#中foreach循环对比for循环的优势和劣势

C#中foreach循环对比for循环的优势和劣势

作者:郑小超  发布时间:2021-12-29 23:50:59 

标签:c#,for循环,foreach循环

前言

循环语句为众多程序员们提供了很大的便利,有while、do...while、for和 foreach。而且foreach语句很简洁,但是它的优点不仅仅在于此,它的效率也是最高的。本文将详细给大家关于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());

C#中foreach循环对比for循环的优势和劣势

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

C#中foreach循环对比for循环的优势和劣势

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

C#中foreach循环对比for循环的优势和劣势

6、当集合元素如List<T>等在使用foreach进行循环时,每循环完一个元素,就会释放对应的资源,代码如下:


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

二、foreach循环的劣势

1、上面说了foreach循环的时候会释放使用完的资源,所以会造成额外的gc开销,所以使用的时候,请酌情考虑

2、foreach也称为只读循环,所以再循环数组/集合的时候,无法对数组/集合进行修改。

3、数组中的每一项必须与其他的项类型相等.

来源:http://www.cnblogs.com/GreenLeaves/p/7401605.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com