Foreach loop traversal and yeild keywords

Source: Internet
Author: User

If you want to traverse an object of the type in foreach, there must be a method for this type: ieumerator getenumerator (). The general practice is to implement the ienumeralbe interface for this type, the getenumerator () method is required for this type. The returned value of getenumerator () is of the ienumerator type. Then write a type that implements the class of the ienumerator interface and returns the object of this type in the getenumerator () method. The type that implements the ienumerable interface is the enumerated type, and the type that implements the ienumerator interface is the enumerator. The yield keyword implements object traversal.

For example:

Namespace _ foreach

{

Class Program

{

Static void main (string [] ARGs)

{

Person p1 = new person ();

Foreach (VAR item in P1)

{

Console. writeline (item );

}

Console. readkey ();

}

}

Public class person: ienumerable <string>
{
Private string [] _ names = {"AA", "BB", "cc", "DD "};
Public string name
{
Get;
Set;
}
Public int age
{
Get;
Set;
}
Public String email
{
Get;
Set;
}

Public ienumerator <string> getenumerator ()

{

For (INT I = 0; I <_ names. length; I ++)

{

Yield return _ Names [I];

If (_ Names [I] = "AA ")

{

Yield break;

}

Else

{

Yield return _ Names [I];

}

}

}

Note: foreach loop traversal is read-only and cannot be used to modify data.

The foreach traversal type is inferred to be object rather than the actual type. You need to implement the generic version interface.

When the return value of the yield statement method is ienumerable <t>, an iteration type is automatically generated.

When the return value of the yield statement method is ienumerator <t>, an iterator is automatically generated.

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.