简体   繁体   中英

What are C# Iterators and Generators, and how could I utilize them

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

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM