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.