foreach的优势

我们都知道,能用foreach遍历访问的对象必须是集合或数组对象,而这些都是靠实现超级接口IEnumerable或声明GetEnumerator方法的类型,而它的好处究竟在哪?
循环语句是编程的基本语句,在C#中除了沿用C语言的循环语句外,还提供了foreach语句来实现循环。那么,在循环操作中尽量使用foreach语句来实现
为了更好的说明foreach的好处,用如下三种不同方式来编写循环语句
int[] nArray=new int[100];
 
//use "foreach"to loop array
foreach(int i in nArray)
Debug.WriteLine(i.ToString());
 
//use "for"to loop array
for(int i=0;i<nArray.Length;i++)
Debug.WriteLine(nArray[i].ToString());
 
//Another way using "for" to loop array
int nLength=nArray.Length
for(int i=0;i<nLength;i++)
Debug.WriteLine(nArray[i].ToString());
foreach语句很简洁,它的效率也是最高的,上述第三种方式是效率最低的,虽然表面上不用每次访问引用类型的属性,但是由于C#是强类型检查,对于数组访问的时候,要对索引的有效值进行判断,即第三种方式相当于如下
// Another way using "for" to loop array
int nLength = nArray.Length;
for( int i = 0; i < nLength; i++ )
{
if(i<nArray.Length)
Debug.WriteLine(nArray[i].ToString());
else
throw new IndexOutOfRangeException();
}

foreach语句除了简洁和高效之外,还存在许多优点:
优点一:不需要考虑数组起始索引是0还是1
优点二:对于多维数组的操作十分方便
int[,] nVisited=new int[8,8];
//use "for" to loop two-dimension array
for(int i=0;i<nVisited.GetLength(0);i++)
    for(int j=0;j<nVisited.GetLength(1);j++)
          Debug.WriteLine(nVisited[i,j].ToString());


//use "foreach" to loop two-dimension array
foreach(int i in nVisited)
Debug.WriteLine(i.ToString());

优点三:foreach完成类型转换操作,尤其是对于ArrayList之类的数据集操作来说,这种转换操作显得更加突出
// Init an arraylist object
        int[] nArray=new int[100];
        ArrayList arrInt=new ArrayList();
        arrInt.AddRange(nArray); 
       
//use "foreach" to loop an arraylist
        foreach(int i in arrInt)
        Debug.WriteLine(i.ToString());
       
//use "for" to loop an arraylist
        for(int i=0;i<arrInt.Count;i++)
        {
            int n=(int)arrInt[i];
            Debug.WriteLine(n.ToString());
        } 
foreach语句中有两个限制:一是不能修改枚举成员 二是不要对集合进行删除操作
如下两种方式是错误的
// Use "foreach" to loop an arraylist
 
        foreach( int i in arrInt )
 
        {
 
            i++;//Can't be compiled
 
            Debug.WriteLine( i.ToString() );
 
        }
 
 
 
        // Use "foreach" to loop an arraylist
 
        foreach( int i in arrInt )
 
        {
 
            arrInt.Remove( i );//It will generate error in run-time
 
            Debug.WriteLine( i.ToString() );
 
        }
对于如上的两个操作,可以用for来实现(PS:对于一个记录集的多条数据删除的问题,由于在一些记录集中进行删除的时候,在删除操作之后相应的索引也发生了变化因此必须要反过来进行删除,大致如下)
// Use "for" to loop an arraylist
       forint i=arrInt.Count-1;i>=0;i--)
       {
           int n=(int) arrInt[i];
           if(n==5)
               arrInt.RemoveAt(i);//Remove data here
           Debug.WriteLine(n.ToString());
       }
 
原文地址:https://www.cnblogs.com/IcreamPrince/p/2588993.html