C#:for && foreach循环

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sss_369/article/details/86533067

1. for循环

C# for循环用法和C++ for循环一样;

for ( init; condition; increment )
{
   statement(s);
}

                                                       

2. foreach循环

C# 也支持 foreach 循环,使用foreach可以迭代数组或者一个集合对象

以下实例有三个部分:

  • 通过 foreach 循环输出整型数组中的元素。
  • 通过 for 循环输出整型数组中的元素。
  • foreach 循环设置数组元素的计算器
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
    System.Console.WriteLine(element);
}

3. 示例:遍历文件下的图像

string imgFile = @"C:\image";
string[] imgPaths = Directory.GetFiles(imgFile, "*.bmp");
int imgCnt = 0;
foreach (string path in imgPaths)
{
    
    Stopwatch sw = new Stopwatch();//计时
    sw.Start();

    Bitmap input = new Bitmap(path);
    Console.WriteLine(path);
               
    sw.Stop();
    Console.WriteLine("getTime:" + sw.ElapsedMilliseconds);
                
    
}

参考文献:

1. http://www.runoob.com/csharp/csharp-for-loop.html

猜你喜欢

转载自blog.csdn.net/sss_369/article/details/86533067