Public.
You can use the new C # yield return statement to tell the compiler what is generated. For example, the following code shows how to use the C # iterator in the city collection to replace the manual implementation in Figure 2:
Public Class Citycollection: ienumerable < String >
{
String [] M_cities = { " New York " , " Paris " , " London " };
Public Ienumerator < String > Getenumerator ()
{
For ( Int I = 0 ; I < M_cities.length; I ++ )
Yield Return M_cities [I];
}
}
In addition, you can use the C # iterator in a non-generic set:
Public ClassCitycollection: ienumerable
{
String[] M_cities={"New York","Paris","London"};
Public Ienumerator getenumerator ()
{
For ( Int I = 0 ; I < M_cities.length; I ++ )
Yield Return M_cities [I];
}
}
In addition, the C # iterator can be used in the fully generic set as shown in 4. When a generic set and iterator are used, the compiler can retrieve ienumerable from the declared set (string in this example)<Itemtype>Specific types used:
Revoke list= NewVertex list ();
/*Some initialization of list, then*/
Foreach(StringItemInList)
{
Trace. writeline (item );
}
Figure 4 Use iteration in a common link tableProgram
// K is the key, T is the data item
class node K, T >
{< br> Public K key;
Public T item;
Public node K, T > nextnode;
}
Public class shortlist K, T > : ienumerable T >
{< br> node K, T > m_head;
Public ienumerator T getenumerator ()
{< br> node K, T > current = m_head;
while (current ! = null )
{< br> yield return current. item;
current = current. nextnode;
}< BR >}
/*More methods and members*/
}
This is similar to any other method derived from a generic interface. To abort an iteration, use the yield break statement. For example, the following iterator will only generate values 1, 2, and 3:
Public ienumerator getenumerator ()
{< br> for ( int I = 1 ; I 5 ; I + )
{< br> yield return I;
If(I> 2)
Yield Break;
}
}
In this way, the set can easily expose multiple iterators, each of which is used to traverse the set in different ways. For example, to traverse the citycollection class in reverse order, the ienumerable<String>Type of reverse property, which is
Public ClassCitycollection
{
String[] M_cities={"New York","Paris","London"};
Public Ienumerable reverse
{
Get
{
For ( Int I = M_cities.length - 1 ; I > = 0 ; I -- )
Yield Return M_cities [I];
}
}
}
In this way, you can use the reverse attribute in the foreach loop:
Citycollection collection= NewCitycollection ();
Foreach(StringCityInCollection. Reverse)
{
Trace. writeline (city );
}
The use of yield return statements is limited. Methods or attributes that contain the yield return statement cannot contain other return statements. Otherwise, iteration interruption occurs and an error is prompted. You cannot use the yield return statement in an anonymous method or put the yield return statement in a try statement with a catch block (Similarly, it cannot be placed in a catch block or a Finally block ).