C#拾遗之foreach迭代语句

C#语言提供了一个for语句循环的捷径,而且还促进了集合类的更为一致,它就是foreach语句。

foreach语句的定义格式为:

foreach(类型 变量 in 集合)

{

子语句;

}

每执行一次内嵌语句,循环变量就依次取集合中的一个元素代入其中,,在这里,循环变量是一个只读型局部变量,如试图改变其值将会发生编译错误。

foreach语句用于列举出集合中所有的元素,foreach语句中的表达式由关键字in隔开的两个项组成。in右边的项是集合名,in左边的项是变量名,用来存放该集合中的每个元素。

foreach语句的优点一:语句简洁,效率高。

用一个遍历数组元素的例子来说明:

先用foreach语句来输出数组中的元素:

<span style="font-size:18px;">int[,] ints =new int[2,3]{{1,2,3},{4,5,6}};foreach (int temp in ints){Console.WriteLine(temp);}Console.ReadLine();</span>

再用for语句输出数组中元素:

<span style="font-size:18px;">int[,] ints =new int[2,3]{{1,2,3},{4,5,6}};for (int i = 0; i < ints.GetLength(0); i++){for (int j = 0; j < ints.GetLength(1); j++){Console.WriteLine(ints[i,j]);}}Console.ReadLine();</span>

这两种代码执行的结果是一样的都是每行一个元素,共6行,元素分别是1 2 3 4 5 6。

在一维数组中还无法体现出foreach语句的简洁性,高效率性,但是在二维数组,甚至多维数组中体现的更为明显和方便,所以在C#语言中要用循环语句提倡使用foreach语句。

foreach语句的优点二:避免不必要的因素

foreach语句的优点三:foreach语句自动完成类型转换

先用foreach语句来实现类型转换操作:在使用ArrayList类时先要引入using System.Collections;

<span style="font-size:18px;">int[] a=new int[3]{1,2,3};ArrayList arrint = new ArrayList();arrint.AddRange(a);foreach (int temp in arrint){Console.WriteLine(temp);}Console.ReadLine();</span>

再来使用for语句来实现:需要进行显式的强制转换

<span style="font-size:18px;">int[] a=new int[3]{1,2,3};ArrayList arrint = new ArrayList();arrint.AddRange(a);for (int i = 0; i < arrint.Count;i++ ){int n = (int)arrint[i];Console.WriteLine(n);}Console.ReadLine();</span>

两个程序输出的结果为:每一行一个元素,分别为1,2,3。 foreach语句对于string类更是简洁:

<span style="font-size:18px;">using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace @foreach{class Program{static void Main(string[] args){string str = "This is an example of a foreach";foreach (char i in str){if (char.IsWhiteSpace(i)){Console.WriteLine(i);//当i为空格时输出并换行}else{Console.Write(i);//当i不为空格时只是输出}}Console.ReadLine();}}}</span>

输出的结果为:每一行一个单词,分别为This, is ,an ,example ,of ,a ,foreach。 对于foreach语句的理解,目前也就知道这多了,随着更深层次的学习,或许会有更好的理解吧。

接受失败,是我们不常听到或看到的一个命题,

C#拾遗之foreach迭代语句

相关文章:

你感兴趣的文章:

标签云: