What is the yield keyword used for in C#?

What is the yield keyword used for in C#?

回答1

The yield keyword actually does quite a lot here.

The function returns an object that implements the IEnumerable<object> interface. If a calling function starts foreaching over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.

The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:

public void Consumer()
{
    foreach(int i in Integers())
    {
        Console.WriteLine(i.ToString());
    }
}

public IEnumerable<int> Integers()
{
    yield return 1;
    yield return 2;
    yield return 4;
    yield return 8;
    yield return 16;
    yield return 16777216;
}

When you step through the example, you'll find the first call to Integers() returns 1. The second call returns 2 and the line yield return 1 is not executed again.

Here is a real-life example:

public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
    using (var connection = CreateConnection())
    {
        using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
        {
            command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    yield return make(reader);
                }
            }
        }
    }
}
  • In this case that would be easier, i'm just using the integer here to show how yield return works. The nice things about using yield return is that it's a very quick way of implementing the iterator pattern, so things are evaluated lazly. – Mendelt Dec 22 '08 at 8:35
  • Also worth noting you can use yield break; when you don't want to return any more items.

 

回答2

https://stackoverflow.com/a/39507/3782855

Recently Raymond Chen also ran an interesting series of articles on the yield keyword.

While it's nominally used for easily implementing an iterator pattern, but can be generalized into a state machine.

No point in quoting Raymond, the last part also links to other uses (but the example in Entin's blog is esp good, showing how to write async safe code).

 

回答3

Yield has two great uses,

  1. It helps to provide custom iteration without creating temp collections.

  2. It helps to do stateful iteration.

In order to explain above two points more demonstratively, I have created a simple video you can watch it here

评论:

The video help me to clearly understand the yield. @ShivprasadKoirala's code project article What is the use of C# Yield ? of the same explanation is also a good source
– Dush
Apr 30, 2015 at 21:46
 
 

What is the use of c# “Yield” keyword ?

Scenario 2:- Stateful iteration<o:p>

Now let us add more complications to the above scenario. Let’s say we want to display running total of the above collection. What do I mean?.


In other words we will browse from 1 to 5 and as we browse we would keep adding the total in variable. So we start with “1” the running total is “1”, we move to value “2” the running total is previous value “1” plus current value “2” i.e. “3” and so on.

Below is the pictorial representation of the running total looks like.

 

In other words we would like to iterate through the collection and as we iterate would like to maintain running total state and return the value to the caller ( i.e. console application). So the function now becomes something as shown below. The “runningtotal” variable will have the old value every time the caller re-enters the function.

 

posted @ 2019-09-18 14:31  ChuckLu  阅读(223)  评论(0编辑  收藏  举报