轻松学习C#的foreach迭代语句


C#语言提供的foreach语句是一个for语句循环的捷径,而且还促进了集合类的更为一致,先来看看它的定义格式:
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语句的优点二:避免不必要的因素
        在C#语言中使用foreach语句不用考虑数组起始索引是几,很多人可能从其他语言转到C#的,那么原先语言的起始索引可能不是1,例如VB或者Delphi语言,那么在C#中使用数组的时候就难免疑问到底使用0开始还是用1开始呢,那么使foreach就可以避免这类问题。
        foreach语句的优点三:foreach语句自动完成类型转换
        这种体现可能通过如上的例子看不出任何效果,但是对于ArrayList之类的数据集来说,这种操作就显得比较突出。
先用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语句的理解,目前也就知道这多了,随着更深层次的学习,或许会有更好的理解吧。

以上就是本文的全部内容,希望对大家的学习有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3