asp.net c# foreach语句遍历数组(1/3)
foreach 语句为数组或对象集合中的每个元素重复一个嵌入语句组。foreach 语句用于循环访问集合以获取所需信息,但不应用于更改集合内容以避免产生不可预知的副作用。
备注
--------------------------------------------------------------------------------嵌入语句为数组或集合中的每个元素继续执行。当为集合中的所有元素完成迭代后,控制传递给 foreach 块之后的下一个语句。
可以在 foreach 块的任何点使用 break 关键字跳出循环,或使用 continue 关键字直接进入循环的下一轮迭代。
foreach 循环还可以通过 goto、return 或 throw 语句退出。
int[,] numbers2d = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2d)
{
system.console.write("{0} ", i);
}该示例的输出为:
9 99 3 33 5 55
然而,对于多维数组,使用嵌套的 for 循环可以更好地控制数组元素。
int[] narray = new int[100];
// use "foreach" to loop array
foreach( int i in narray )
debug.writeline( i.tostring() );
// use "for" to loop array
for( int i = 0; i < narray.length; i++ )
debug.writeline( narray[i].tostring() );
// another way using "for" to loop array
int nlength = narray.length;
for( int i = 0; i < nlength; i++ )
debug.writeline( narray[i].tostring() );
很明显,foreach语句很简洁,但是它的优点不仅仅在于此,它的效率也是最高的。可能很多人认为最后一种的效率会更高,因为表面上看着不用每次访问引用类型的属性。可是它却是三者当中,效率最低的。因为c#是强类型检查,那么对于数组访问的时候,要对索引的有效值进行判断,那么对于最后一种代码实际产生的效果如同下面的代码一样。
// another way using "for" to loop array
int nlength = narray.length;
for( int i = 0; i < nlength; i++ )
{
if( i < narray.length )
debug.writeline( narray[i].tostring() );
else
throw new indexoutofrangeexception();
}
1 2 3补充:asp.net教程,.Net开发