Use of the yield keyword and the yield keyword
What does yield mean in Chinese?
The translation on Kingsoft is:
Vt.Yield and surrender; Production; Profit; No objection
Vi.Give up and give in; Profits; Concession, return
N.Yield and yield; Investment income; Yield, breakdown; Product
I personally think that the yield keyword in C # Means concession, concession, and authorization.
The yield keyword is mainly used in the yield iterator block. When yield is used, the C # compiler creates a state machine to save the status in the current iterator block, return a variable to be returned, and exit the current iterator block temporarily. Then, when the iterator block needs to be called next time, the compiler will return the variable based on the previously saved status and then perform the operation you defined.
The following is an example:
Create an IEnumerableExample class to implement the IEnumerable interface, and use the yield keyword in the GetEnumerator method to return variables.
public class IEnumerableExample:IEnumerable { private object[] values; public IEmuerableExample(object[] values) { this.values = values; } public IEnumerator GetEnumerator() { for(int i=0;i<values.Length;i++) { yield return values[i]; } } }
Main function:
static void Main(string[] args) { object[] values={'a','b','c','d'}; IEmuerableExample ie = new IEmuerableExample(values); foreach (var item in ie) { Console.WriteLine(item); } Console.ReadKey(); }
Output:
This is my ignorance of the yield keyword. please correct me if you have any mistakes. Thank you.