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);
}
这个以前有人问过,这个也是别人的答案,以后多搜索以前的帖子
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);
}
这个以前有人问过,这个也是别人的答案,以后多搜索以前的帖子
例子太多了.
对数组
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);
}
}
}