Use of the yield keyword and the yield keyword

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.