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);
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP