在C#中,有几种循环方式,do, while, for,foreach。好像foreach是用的比较少的一种,而其实从.net 1.1的版本以后,foreach循环是效率最高的一种。比如下面几个例子:
int [] foo = new int[100];
// Loop 1:
foreach ( int i in foo)
Console.WriteLine( i.ToString( ));
// Loop 2:
for ( int index = 0;
index < foo.Length;
index++ )
Console.WriteLine( foo[index].ToString( ));
// Loop 3:
int len = foo.Length;
for ( int index = 0;
index < len;
index++ )
Console.WriteLine( foo[index].ToString( ));
有些人可能会觉得第三种是效率最高的,因为它把Length提到了循环体外。实际上在C#编译器产生的代码中,为了安全性,每次循环都要检查边界,所以即使你的代码把Length放在循环体外,编译器产生的代码仍然要在每次循环中检查Length的边界情况。而编译器可以自动为foreach语句产生最适合,最有效率的代码。
使用foreach还有一个好处是如果你改变了集合的类型,不会影响到其他的代码段,比如开始你用的是数组,后来又改成了ArrayList。如
果你用的是其他的循环方式,就必须修改相应的代码,而使用foreach就不会有这样的情况。
//int [] foo = new int[100];
ArrayList foo = new ArrayList( 100 );
int sum = 0;
for ( int index = 0;
// won't compile: ArrayList uses Count, not Length
index < foo.Length;
index++ )
// won't compile: foo[ index ] is object, not int.
sum += foo[ index ];