什么是C#迭代器和生成器,以及如何使用它们

时间:2021-09-26 15:15:23

I am a VB.Net developer, kind of newbie in C#, While looking in C# documentation I came through Iterators and Generators, could not fully understand the use, I there anyone who can explain (in vb perceptive; if possible)

我是一名VB.Net开发人员,在C#中有点新手,在查看C#文档时,我通过迭代器和生成器来了,无法完全理解使用,我有任何人可以解释(在vb中有洞察力;如果可能的话)

1 个解决方案

#1


19  

Iterators are an easy way to generate a sequence of items, without having to implement IEnumerable<T>/IEnumerator<T> yourself. An iterator is a method that returns an IEnumerable<T> that you can enumerate in a foreach loop.

迭代器是生成一系列项的简单方法,无需自己实现IEnumerable / IEnumerator 。迭代器是一个返回IEnumerable 的方法,您可以在foreach循环中枚举它。

Here's a simple example:

这是一个简单的例子:

public IEnumerable<string> GetNames()
{
    yield return "Joe";
    yield return "Jack";
    yield return "Jane";
}

foreach(string name in GetNames())
{
    Console.WriteLine(name);
}

Notice the yield return statements: these statement don't actually return from the method, they just "push" the next element to whoever is reading the implementation.

请注意yield return语句:这些语句实际上并不从方法返回,它们只是将下一个元素“推送”给正在读取实现的人。

When the compiler encounters an iterator block, it actually rewrites it to a state machine in a class that implements IEnumerable<T> and IEnumerator<T>. Each yield return statement in the iterator corresponds to a state in that state machine.

当编译器遇到迭代器块时,它实际上将它重写为实现IEnumerable 和IEnumerator 的类中的状态机。迭代器中的每个yield return语句对应于该状态机中的状态。

See this article by Jon Skeet for more details on iterators.

有关迭代器的更多详细信息,请参阅Jon Skeet撰写的这篇文章。

#1


19  

Iterators are an easy way to generate a sequence of items, without having to implement IEnumerable<T>/IEnumerator<T> yourself. An iterator is a method that returns an IEnumerable<T> that you can enumerate in a foreach loop.

迭代器是生成一系列项的简单方法,无需自己实现IEnumerable / IEnumerator 。迭代器是一个返回IEnumerable 的方法,您可以在foreach循环中枚举它。

Here's a simple example:

这是一个简单的例子:

public IEnumerable<string> GetNames()
{
    yield return "Joe";
    yield return "Jack";
    yield return "Jane";
}

foreach(string name in GetNames())
{
    Console.WriteLine(name);
}

Notice the yield return statements: these statement don't actually return from the method, they just "push" the next element to whoever is reading the implementation.

请注意yield return语句:这些语句实际上并不从方法返回,它们只是将下一个元素“推送”给正在读取实现的人。

When the compiler encounters an iterator block, it actually rewrites it to a state machine in a class that implements IEnumerable<T> and IEnumerator<T>. Each yield return statement in the iterator corresponds to a state in that state machine.

当编译器遇到迭代器块时,它实际上将它重写为实现IEnumerable 和IEnumerator 的类中的状态机。迭代器中的每个yield return语句对应于该状态机中的状态。

See this article by Jon Skeet for more details on iterators.

有关迭代器的更多详细信息,请参阅Jon Skeet撰写的这篇文章。