How is yield used in C#?
In C#, the yield keyword is used to define an iterator method that can return an enumerable sequence.
The syntax for using the yield keyword is as follows:
yield return expression;
In this case, “expression” is the value to be returned.
When using the yield return statement, the iterator method will return the next element in a sequence and continue executing the method on the next iteration.
Here is an example of using yield:
public static IEnumerable<int> GetNumbers()
{
yield return 1;
yield return 2;
yield return 3;
}
// 调用迭代器方法
foreach (int number in GetNumbers())
{
Console.WriteLine(number);
}
The above code defines an iterator method called GetNumbers, which will return a sequence containing the numbers 1, 2, and 3. When calling the GetNumbers method in a foreach loop, each iteration will return the next element in the sequence, assign it to the number variable, and then output it to the console.
Using yield makes it easy to create and use iterators without needing to explicitly implement the IEnumerable and IEnumerator interfaces.