C# 迭代器

迭代器是用于迭代列表、元组等集合的方法。使用迭代器方法,我们可以遍历对象并返回其元素。


创建迭代器方法

要创建迭代器方法,我们使用 yield return 关键字返回值。

迭代器方法的返回类型是 IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>

我们可以将迭代器方法定义为

returnType methodName()
{
    yield return returnValue;
}

这里,

  • methodName() - 迭代器方法的名称
  • returnType - 方法的返回类型
  • returnValue - 方法返回的值

注意:要了解更多关于 yield return 的信息,请访问 C# yield


示例 1:迭代器方法

using System;
using System.Collections;
class Program
{
// define an iterator method static IEnumerable getString()
{ yield return "Sunday"; yield return 2; } static void Main() { // display return values of getString() foreach (var items in getString()) { Console.WriteLine(items); } } }

输出

Sunday
2

这里,getString() 是一个迭代器方法,它使用 yield return 返回 "Sunday"2


示例 2:带列表的迭代器方法

using System;
using System.Collections.Generic;
class Program
{
// define an iterator method static IEnumerable<int> getList()
{ // create a list List<int> myList = new List<int>(); // add elements to the list myList.Add(1); myList.Add(2); myList.Add(4);
// iterate the elements of myList foreach (var values in myList) { // return elements of myList which are divisible by 2 if (values % 2 == 0) yield return values; }
} static void Main() { // display return values of getList() foreach (var items in getList()) { Console.WriteLine(items); } } }

输出

2
4

这里,我们定义了一个名为 getList() 的迭代器方法,其返回类型为 IEnumerable<int>

getList() 方法内部,我们使用 yield return 遍历了 myList。请注意以下代码:

// iterate the elements of myList  
foreach (var values in myList)
{
    // return elements of myList which are divisible by 2
if (values % 2 == 0) yield return values;
}

在这里,yield return 会保留当前代码的位置,并将控制权返回给调用者(即 Main() 中的 foreach)。

Main() 方法中,foreach 循环会打印 yield return 返回的值。请注意下面的代码:

// display return values of getList()  
foreach (var items in getList())
{ Console.WriteLine(items); }

然后,foreach 会再次调用 getList() 方法进行下一次迭代。这个过程会一直持续,直到 myList 中的所有元素都被迭代。

这样,我们就可以在 C# 中对 List<T> 等集合进行自定义迭代。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战