using System;
using System.Diagnostics;
class Test
{
    static void Main()
    {
        int[] lists = Method();
        Stopwatch stop = new Stopwatch();
        stop.Start();
        for (int i = 0; i < lists.Length; i++)
        {        }
        Console.WriteLine(stop.ElapsedMilliseconds);
        stop.Reset();
        stop.Start();
        foreach (int a in lists)
        {        }
        Console.WriteLine(stop.ElapsedMilliseconds);
        Console.ReadKey();
    }
    static int[] Method()
    {
        int[] ints = new int[10000000];
        for (int i = 0; i < 10000000; i++)
        {
            ints[i] = i + 1;
        }
        return ints;
    }
}33
62

解决方案 »

  1.   

    foreach需要调用IEnumerator,IEnumerable接口  
      

  2.   

    ls说的如果是对的,那么foreach根本就用不到了直接for搞定!
      

  3.   

    ...
    ArrayList list=new ArrayList();
    list.Add(1);
    list.Add("a");
    list.Add("vb");foreach(strig c in list)
    {
        c=c.SubString(1);
    }for(int i=0;i<list.count;i++)
    {
       object o=list[i];
       if(object.GetType()==typeof(string))
       {
            string c=(string)o;
            c=c.SubString(1); 
       }
    }
      

  4.   

    Effective C#上有专门介绍for和foreach的区别的
      

  5.   

    我个人比较偏向于foreach
    虽然有的时候for比foreach快
    但是大多数foreach效率都要好些
    而且foreach的代码更加简练看看这个吧http://www.cnblogs.com/WuCountry/archive/2007/02/27/658710.html
      

  6.   

    我昏迷……for里面是个空的,有啥可比性?就是吧i自增到lists.Length而已,说不定还被编译器优化了……