foreach 語句 針對實作迭代器模式的集合逐一枚舉元素,迴圈變數為唯讀區域變數。
foreach (type identifier in expression) embedded-stmt
型別 C 為集合型別,若:
public GetEnumerator() 回傳 E(結構/類別/介面)。E 有 public bool MoveNext()。E 有 public Current { get; } 屬性。Current 的型別即為元素型別。
ref/out 傳遞(編譯錯誤)。
// 假設 Prime 為實作 IEnumerable 的集合
// MyInt 為 200~300 範圍包裝型別
foreach (MyInt x in Prime)
Console.WriteLine(x); // 輸出 200~300 間質數
行為同 for/while。