for 和 foreach 的区别,该怎么处理

for 和 foreach 的区别
平时用for循环最多,用foreach不是很多 

只知道foreach循环是一个只读的循环
而且感觉foreach像一个黑盒,你不知道它到底能够循环多少次;
而 for 的话就很清楚的知道循环的次数

其次,所有的for都可以用foreach代替吗?反过来所有的foreach都可以写出相应的for吗?


其他还有什么区别,请大家讨论一下吧

------解决方案--------------------
C#代码:
public int LoopTest()
{
int s=0;

int[] array={2,3,4,5,6,7,8,9};
 
for(int k=0;k<=7;k++)
{
s+=array[k];
}
  

foreach(int a in array)
{
s+=a;
}

return s;

}

 

IL代码:
.method public hidebysig instance int32 LoopTest() cil managed
{
// 代码大小 78 (0x4e)
.maxstack 3
.locals init ([0] int32 s,
[1] int32[] 'array',
[2] int32 k,
[3] int32 a,
[4] int32 CS$00000003$00000000,
[5] int32[] CS$00000007$00000001,
[6] int32 CS$00000008$00000002)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: ldc.i4.8
IL_0003: newarr [mscorlib]System.Int32
IL_0008: dup
IL_0009: ldtoken field valuetype '<PrivateImplementationDetails>'/'$$struct0x6000002-1' '<PrivateImplementationDetails>'::'$$method0x6000002-1'
IL_000e: call void [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array,
valuetype [mscorlib]System.RuntimeFieldHandle)
IL_0013: stloc.1
IL_0014: ldc.i4.0
IL_0015: stloc.2
IL_0016: br.s IL_0022 //for 开始的地方
IL_0018: ldloc.0
IL_0019: ldloc.1
IL_001a: ldloc.2
IL_001b: ldelem.i4
IL_001c: add
IL_001d: stloc.0
IL_001e: ldloc.2
IL_001f: ldc.i4.1
IL_0020: add
IL_0021: stloc.2
IL_0022: ldloc.2
IL_0023: ldc.i4.7
IL_0024: ble.s IL_0018 //for 结束的地方
IL_0026: ldloc.1 //foreach 从这里开始
IL_0027: stloc.s CS$00000007$00000001
IL_0029: ldc.i4.0
IL_002a: stloc.s CS$00000008$00000002
IL_002c: br.s IL_003e
IL_002e: ldloc.s CS$00000007$00000001
IL_0030: ldloc.s CS$00000008$00000002
IL_0032: ldelem.i4
IL_0033: stloc.3
IL_0034: ldloc.0
IL_0035: ldloc.3
IL_0036: add
IL_0037: stloc.0
IL_0038: ldloc.s CS$00000008$00000002
IL_003a: ldc.i4.1
IL_003b: add
IL_003c: stloc.s CS$00000008$00000002
IL_003e: ldloc.s CS$00000008$00000002
IL_0040: ldloc.s CS$00000007$00000001
IL_0042: ldlen
IL_0043: conv.i4
IL_0044: blt.s IL_002e //foreach结束的地方
IL_0046: ldloc.0
IL_0047: stloc.s CS$00000003$00000000 //此乃自动生成的一个变量,保存返回值,void时没有
IL_0049: br.s IL_004b
IL_004b: ldloc.s CS$00000003$00000000
IL_004d: ret
} // end of method Class1::LoopTest


------解决方案--------------------
foreach实际上是循环语句的一种.为数组元素提供了一种更方便的访问方式!
------解决方案--------------------
for有绝对优势,不管是性能和操作!
------解决方案--------------------
foreach不能完全代替for,但能代替的地方有时候使用foreach更方便,比如一个数组里有好多的对象,但你不知道有几个,这时用foreach可以一个一个的把他们都迭代出来。
------解决方案--------------------
详细参考:http://topic.csdn.net/t/20040911/14/3362835.html
------解决方案--------------------
在 foreach
里你删除一个
对象试试!


------解决方案--------------------