1、foreach循环与for循环输出结果比较,能达到一样的输出效果。
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ForeachApplication
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int[] a = { 1,5,9,20,16};
13 Console.WriteLine("使用foreach ....结果");
14 foreach (int i in a)
15 {
16 Console.WriteLine("{0}",i);
17 }
18 Console.WriteLine("使用for ....结果");
19 for (int j = 0; j < 5; j++)
20 Console.WriteLine("{0}",a[j]);
21 }
22 }
23 }
2、foreach与 for 的主要区别在于 foreach 循环对数组内容进行只读访问,所以不能改变任何元素的值。而for 循环可以,看下面代码:
foreachfor
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace ForeachApplication
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 int[] a = { 1,5,9,20,16};
13 Console.WriteLine("使用foreach ....结果");
14 foreach (int i in a)
15 {
16 Console.WriteLine("{0}",i);
17 }
18 Console.WriteLine("使用for ....结果");
19 for (int j = 0; j < 5; j++)
20 // Console.WriteLine("{0}",a[j]);
21 {
22 if (a[j] > 10)
23 {
24 a[j] = 7;
25 }
26
27 }
28 Console.WriteLine("把数组中的大于10的数,修改成7后....输出结果");
29 foreach (int i in a)
30 {
31 Console.WriteLine("{0}", i);
32 }
33 }
34 }
35 }