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

2019-12-30 11:17:53于海丽

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

再来

 

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

两个程序输出的结果为:每一行一个元素,分别为1,2,3。

foreach语句对于string类更是简洁:

 

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