C#中的迭代函式
迭代器方法對集合執行自定義迭代。它使用 yield return 語句並一次返回一個元素。迭代器記住當前位置,並在下一次迭代中返回下一個元素。
以下是示例 −
示例
using System;
using System.Collections.Generic;
using System.Linq;
namespace Demo {
class Program {
public static IEnumerable display() {
int[] arr = new int[] {99,45,76};
foreach (var val in arr) {
yield return val.ToString();
}
}
public static void Main(string[] args) {
IEnumerable ele = display();
foreach (var element in ele) {
Console.WriteLine(element);
}
}
}
}輸出
99 45 76
上面我們有一個迭代器方法 display(),它使用 yield 語句每次返回一個元素 −
public static IEnumerable display() {
int[] arr = new int[] {99,45,76};
foreach (var val in arr) {
yield return val.ToString();
}
}結果被儲存並在每次迭代中輸出 −
IEnumerable ele = display();
foreach (var element in ele) {
Console.WriteLine(element);
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP