This example applies to. NET Framework 2.0 and later versions.
A simple class 1 Internal Class Goodsshelf
2 {
3 // Cargo List
4 String [] Goods = { " First thing " , " Second thing " , " Third thing " , " Fourth thing " , " Th thing " };
5
6 /// <Summary>
7 /// Get iterator
8 /// </Summary>
9 /// <Returns> </returns>
10 Public Ienumerator getenumerator ()
11 {
12 For ( Int I = 0 ; I < Goods. length; I ++ )
13 {
14 Yield Return Goods [I];
15 }
16 }
17
18 }
To use a foreach loop, you must provide it with a type that supports iteration. That is, the implementation of an ienumerator or ienumerable interface is provided. The type defined in the preceding example does not implement any of the two interfaces, however, we can take the initiative to give him a getenumerator () method that returns ienumerator or ienumerable.
The getenumerator () method returnsYield return,YieldThe keyword is used in the iterator block to provide a value to the enumerated number object or send an iteration end signal. For more information about the yield keywords, see.
Test example
1 Class Program
2 {
3 Static Void Main ( String [] ARGs)
4 {
5 Goodsshelf goods = New Goodsshelf ();
6 Foreach (VAR item In Goods)
7 {
8 Console. writeline (item );
9 }
10 }
11
12 }
Output result
First thing
Second thing
Third thing
Fourth thing
Th thing