-->

What is the use of the “yield” keyword in C#? [dup

2019-05-26 21:53发布

问题:

Possible Duplicate:
Proper Use of yield return

What is the use of the yield keyword in C#?

I didn't understand it from the MSDN reference... can someone explain it to me please?

回答1:

I'm going to try and give you an example

Here's the classical way of doing, which fill up a list object and then returns it:

private IEnumerable<int> GetNumbers()
{
    var list = new List<int>();
    for (var i = 0; i < 10; i++)
    {
        list.Add(i);
    }
    return list;
}

the yield keyword returns items one by one like this :

private IEnumerable<int> GetNumbers()
{
    for (var i = 0; i < 10; i++)
    {
        yield return i;
    }
}

so imagine the code that calls the GetNumbers function as following:

foreach (int number in GetNumbers())
{
   if (number == 5)
   {
       //do something special...
       break;
   }
}

without using yield you would have to generate the whole list from 0-10 which is then returned, then iterated over until you find the number 5.

Now thanks to the yield keyword, you will only generate numbers until you reach the one you're looking for and break out the loop.

I don't know if I was clear enough..



回答2:

my question is, when do I use it? Is there any example out there where I have there is no other choice but using yield? Why did someone feel C# needed another keyword?

The article you linked provided a nice example of when and how it is used.

I hate to quote an article you yourself linked too, but incase it's too long, and you didn't read it.

The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block.

public static System.Collections.IEnumerable Power(int number, int exponent)
{
    int counter = 0;
    int result = 1;
    while (counter++ < exponent)
    {
        result = result * number;
        yield return result;
    }
}

In the above example, the yield statement is used inside an iterator block. When the Power method is invoked, it returns an enumerable object that contains the powers of a number. Notice that the return type of the Power method is System.Collections.IEnumerable, an iterator interface type.

So the compiler automatically generates a IEnumerable interfaced based on the things that were yielded during the method's execution.

Here is a simplified example, for the sake of completeness:

public static System.Collections.IEnumerable CountToTen()
{
    int counter = 0;
    while (counter++ < 10)
    {
        yield return counter;
    }
}

public static Main(string[]...)
{
    foreach(var i in CountToTen())
    {
        Console.WriteLine(i);
    }
}