C++ 和 C# 中的 Foreach


C++ 中的 Foreach

C++ 11 引入 foreach 迴圈來遍歷每個元素。如下例所示 −

示例

 即時演示

#include <iostream>
using namespace std;

int main() {
   int myArr[] = { 99, 15, 67 };

   // foreach loop
   for (int ele : myArr)
   cout << ele << endl;
}

輸出

99
15
67

C# 中的 Foreach

我們來看一個 C# 中 foreach 的示例,它遍歷集合中的項 −

示例

 即時演示

using System;

namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int [] n = new int[10]; /* n is an array of 10 integers */

         for ( int i = 0; i < 10; i++ ) {
            n[i] = i + 100;
         }
         /* output each array element's value */
         foreach (int j in n ) {
            int i = j-100;
            Console.WriteLine("Element[{0}] = {1}", i, j);
         }
         Console.ReadKey();
      }
   }
}

輸出

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

更新時間:2020-06-22

606 次瀏覽

開啟您的職業生涯

透過學習課程並獲得認證

開始學習
廣告