迭代器是用于迭代列表、元组等集合的方法。使用迭代器方法,我们可以遍历对象并返回其元素。
创建迭代器方法
要创建迭代器方法,我们使用 yield return
关键字返回值。
迭代器方法的返回类型是 IEnumerable
、IEnumerable<T>
、IEnumerator
或 IEnumerator<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>
等集合进行自定义迭代。