Use the yield keyword to implement foreach traversal for a custom set

Source: Internet
Author: User

Generally, when we create a custom set, we can only implement the ienumerable interface (which may also implement the ienumerator Interface) to support foreach traversal)

However, we can also use the iterator Method built with the yield keyword to implement foreach traversal, And the custom set does not need to implement the ienumerable interface.

Note: although you do not need to implement the ienumerable interface, the method of the iterator must be named getenumerator (), and the returned value must also be of the ienumerator type.

The instance code and simple instructions are as follows:

1 class person 2 {3 Public string name; 4 Public void sayhi () 5 {6 console. writeline ("Hello: {0}", this. name); 7} 8} 9 // very simple custom set (-simple to add, delete, index, and other functions are not implemented) this class does not implement the ienumerable interface 10 class personlist11 {12 person [] pers = new person [4]; 13 public personlist () 14 {15 pers [0] = new person () {name = "1"}; 16 pers [1] = new person () {name = "2"}; 17 pers [2] = new person () {name = "3"}; 18 pers [3] = new person () {name = "4 "}; 19 20} 21 // simple iterator Method 22 public ienumerator getenumerator () 23 {24 25 foreach (person item in pers) 26 {27 // yield return is used to return an element of the set and move it to 28 yield return item on the next element; 29} 30 31} 32} 33 class program34 {35 static void main (string [] ARGs) 36 {37 personlist list = new personlist (); 38 foreach (person item in List) 39 {40 item. sayhi (); 41} 42 console. readline (); 43} 44}

 

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.