假设我们拥有下面的集合
就会报错
i是一个迭代变量,无法为它赋值
切记切记
1
System.Collections.ArrayList list
=
new
System.Collections.ArrayList();
2
list.Add(
1
);
3
list.Add(
12
);
4
list.Add(
3
);
5
list.Add(
56
);
System.Collections.ArrayList list
=
new
System.Collections.ArrayList();2
list.Add(
1
);3
list.Add(
12
);4
list.Add(
3
);5
list.Add(
56
);
现在我们要遍历这个集合,我们有两套方案
1、我们用for遍历
1
int
tmp
=
0
;
2
for
(
int
i
=
1
; i
<
list.Count;i
++
)
3
{
4
tmp += (int)list[i];
5
}
6
7
System.Console.WriteLine(tmp);
int
tmp
=
0
;2
for
(
int
i
=
1
; i
<
list.Count;i
++
) 3
{4
tmp += (int)list[i];5
}
6

7
System.Console.WriteLine(tmp);
使用for遍历,我们可以控制对集合中的局部数据进行遍历。但是,从ArrayList中获取的数据要进行显示的数据类型转换。
2、我们使用foreach遍历
1
tmp
=
0
;
2
3
foreach
(
int
i
in
list) //指定类型int
4
{
5
tmp += i;
6
}
7
System.Console.WriteLine(tmp);
tmp
=
0
;2

3
foreach
(
int
i
in
list) //指定类型int4
{5
tmp += i;6
}
7
System.Console.WriteLine(tmp);
使用foreach将自动迭代每个集合中的元素,且使用foreach表达式中指定的类型进行自动转换。不必显示转换。
当需要迭代集合中所有元素且不关心先后次序时,建议使用foreach。因为大部分情况下在处理集合时,初始值和最终值的概念没有意义,而且你也不必知道集合中包含多少元素。
不过,当你需要将循环的每次迭代与控制变量相关联并可确定该变量的初始值和最终值时,那就用for,比如你需要明确知道元素在集合中的位置时。
除了上面的不同外,for和foreach还有一个很大的不同
1
int
[] iarr
=
new
int
[]
{ 1, 2, 3, 4, 5, 6, 7, 8 }
;
2
for
(
int
i
=
0
; i
<=
iarr.Length
-
1
; i
++
)
3
{
4
System.Console.WriteLine(iarr[i]++);
5
}
int
[] iarr
=
new
int
[]
{ 1, 2, 3, 4, 5, 6, 7, 8 }
;2
for
(
int
i
=
0
; i
<=
iarr.Length
-
1
; i
++
)3
{4
System.Console.WriteLine(iarr[i]++);5
}
输出的结果是
1
2
3
4
5
6
7
8
但是
1
int
[] iarr
=
new
int
[]
{ 1, 2, 3, 4, 5, 6, 7, 8 }
;
2
foreach
(
int
i
in
iarr)
3
{
4
//i是一个迭代变量,无法为它赋值
5
System.Console.WriteLine(i++);
6
}
int
[] iarr
=
new
int
[]
{ 1, 2, 3, 4, 5, 6, 7, 8 }
;2
foreach
(
int
i
in
iarr)3
{4
//i是一个迭代变量,无法为它赋值 5
System.Console.WriteLine(i++);6
}
就会报错
i是一个迭代变量,无法为它赋值
切记切记
本文转自shyleoking 51CTO博客,原文链接:http://blog.51cto.com/shyleoking/806266