当前位置: 移动技术网 > IT编程>开发语言>c# > 轻松学习C#的foreach迭代语句

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

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语句的理解,目前也就知道这多了,随着更深层次的学习,或许会有更好的理解吧。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网