for循環示例:
static void Main(string[] args) { string[] s = new string[] { "a,b,c,d,e,f,g" }; for (int i = 0; i < s.Length; i++) { Console.WriteLine(s[i]); } Console.ReadKey(); }
foreach循環示例:
static void Main(string[] args) { string[] s = new string[] { "a,b,c,d,e,f,g" }; foreach (string item in s) { Console.WriteLine(item); } Console.ReadKey(); }
總結:
for循環需給初值,步長,末值,foreach則不需要,它是自動遍歷集合體中所有值
for循環可用於任何重復行為,foreach循環只能用於遍歷
foreach循環遍歷速度比for循環快