C# Yield Return: Usage Guide
In C#, the yield return is used to create an iterator that allows a method to return elements from a sequence each time it is called. Using yield return helps simplify the implementation of iterators, making the code more concise and readable.
When using yield return in a method, the method becomes an iterator method that allows iterating over a sequence of elements using a foreach loop. Each time the iterator method is called, it will execute until the yield return statement, returning the value of the expression as the current element to the caller, and continuing execution from the line after the yield return statement in the next call.
Here is a simple example that uses yield return:
public static IEnumerable<int> GetNumbers()
{
yield return 1;
yield return 2;
yield return 3;
}
// 调用GetNumbers方法
foreach (int num in GetNumbers())
{
Console.WriteLine(num);
}
In the example above, the GetNumbers method is an iterator method that returns a sequence of integers containing 1, 2, and 3 using the yield return keyword. Within a foreach loop, each element can be iterated and printed out one by one.