foreach()语句可以转换为使用for(),如
foreach(string s in comboBox1.Items)
{
  Console.WriteLine(s);
}等价于:
string s;
for(int i=0; i < comboBox1.Items.Count; i++)
{
  s = (string)comboBox1.Items[i];
  Console.WriteLine(s);
}
这个以前有人问过,这个也是别人的答案,以后多搜索以前的帖子

解决方案 »

  1.   

    foreach 语句为数组或对象集合中的每个元素重复一个嵌入语句组。foreach 语句用于循环访问集合以获取所需信息,但不应用于更改集合内容以避免产生不可预知的副作用.
    例子太多了.
    对数组
    using System;
    class MainClass 
    {
       public static void Main() 
       {
          int odd = 0, even = 0;
          int[] arr = new int [] {0,1,2,5,7,8,11};      foreach (int i in arr) 
          {
             if (i%2 == 0)  
                even++;      
             else 
                odd++;         
          }      Console.WriteLine("Found {0} Odd Numbers, and {1} Even Numbers.",
                            odd, even) ;
       }
    }
    对集合
    // statements_foreach_collections.cs
    // Using foreach with C#-specific collections:
    using System;// Declare the collection:
    public class MyCollection 
    {
       int[] items;   public MyCollection() 
       {
          items = new int[5] {12, 44, 33, 2, 50};
       }   public MyEnumerator GetEnumerator() 
       {
          return new MyEnumerator(this);
       }   // Declare the enumerator class:
       public class MyEnumerator 
       {
          int nIndex;
          MyCollection collection;
          public MyEnumerator(MyCollection coll) 
          {
             collection = coll;
             nIndex = -1;
          }      public bool MoveNext() 
          {
             nIndex++;
             return(nIndex < collection.items.GetLength(0));
          }      public int Current 
          {
             get 
             {
                return(collection.items[nIndex]);
             }
          }
       }
    }public class MainClass 
    {
       public static void Main() 
       {
          MyCollection col = new MyCollection();
          Console.WriteLine("Values in the collection are:");      // Display collection items:
          foreach (int i in col) 
          {
             Console.WriteLine(i);
          }
       }
    }
      

  2.   

    同意1楼的,一看就能明白,for 语句,你可以控制循环的次数,foreach没有测试条件,所以你不知道集合中有多少个项,也没有退出循环的内置机制,不能控制循环的退出时间。