Create elegant code in Visual C #2.0 3

Source: Internet
Author: User
Iterator implementation
The compiler maintains the iteration state by generating Nested classes. When in a foreach loop (or in a direct iterationCode) When the iterator is called for the first time, the compiler generates compiler for the compilation generated by the getenumerator function.
- Generated) the code will create a new iterator object with a reset state (that is, an instance of the nested class ). When foreach calls the movenext method of the iterator cyclically, it starts to execute where the previous yield return statement was stopped. As long as the foreach loop is executed, the iterator will maintain its State. However, the iterator object (and its State) is inconsistent among multiple foreach loops. Therefore, it is safe to call foreach again because a new iterator object is generated and a new iteration starts. This is why ienumerable < Itemtype > The reason why the reset method is not defined.

But how is the nested iterator class implemented? And how to manage its status? The compiler converts a standard method into a method that can be called multiple times. This method uses a simple state machine to resume execution after the previous yield return statement. All developers need to do is to use the yield return statement to indicate what the compiler generates and when to generate it. The compiler is intelligent enough to connect multiple yield return statements in the order they appear:

Public   Class Citycollection: ienumerable
{
Public Ienumerator getenumerator ()
{
Yield   Return   " New York " ;
Yield   Return   " Paris " ;
Yield   Return   " London " ;
}
}

Let's take a look at the getenumerator method of the class displayed in the following lines of code:

Public class mycollection: ienumerable
{< br>
Public ienumerator getenumerator ()
{< br>
// some iteration code that uses yield return
}< BR >}

When the compiler encounters a class member with the yield return statement, it inserts a class member named getenumerator $<Random unique number>_ Ienumeratorimpl nested class definition, as shown in C # pseudocode in 5. (Remember, all the features discussed in this article, including the names of classes and fields generated by the compiler, will change, and in some cases, it may even happen completely. You should not try to use reflection to obtain these Implementation Details and expect consistent results .)

Public   Class Mycollection: ienumerable < String >
{
Public   Virtual Ienumerator < String > Getenumerator ()
{
Getenumerator $0003 _ ienumeratorimpl impl;
Impl
=   New Getenumerator $0003 _ ienumeratorimpl;
Impl.
< This >   =   This ;
Return Impl;
}

Private   Class Getenumerator $0003 _ ienumeratorimpl:
Ienumerator
< String >
{
Public Mycollection < This > ; // Back Reference to the Collection
String $ _ Current;

// State Machine Members go here
String Ienumerator < String > . Current
{
Get
{
Return $ _ Current;
}
}

bool ienumerator string > . movenext ()
{< br>
// state machine management
}

Idisposable. Dispose ()
{
//State Machine cleanup if required
}
}
}

Figure 5 compiler-generated iterationsProgram

Nested classes implement the same ienumerable interface returned from class members. The compiler uses an instantiated nested type to replace the code in the class member, and assigns a reference pointing to the set to the this member variable of the nested class, similar to the manual implementation shown in figure 2. In fact, this nested class is a class that implements the ienumerator interface.

Recursive Iteration
When recursive iteration is performed on a data structure such as a binary tree or graph containing connected nodes, the iterator truly shows its advantages. Manual implementation of a recursive iterator is quite difficult, but it is easy to use a C # iterator. Consider the binary tree in figure 6. TheSource codeContains the complete implementation of this binary tree.

class node T >
{< br>
Public node T leftnode;
Public node T > rightnode;
Public T item;
}

Public class binarytree T >
{< br> node
T > m_root;

Public VoidAdd (ParamsT [] items)
{
Foreach(T itemInItems)
Add (item );
}

Public VoidAdd (T item)
{}

PublicIenumerable<T>Inorder
{
Get
{
ReturnScaninorder (m_root );
}
}

Ienumerable < T > Scaninorder (node < T > Root)
{
If (Root. leftnode ! =   Null )
{
Foreach (T item In Scaninorder (root. leftnode ))
{
Yield   Return Item;
}
}

Yield ReturnRoot. item;

If (Root. rightnode ! =   Null )
{
Foreach (T item In Scaninorder (root. rightnode ))
{
Yield   Return Item;
}
}
}
}

Figure 6 implement recursive Iteration

This binary tree stores some items in the node. Each node has a value of type T (item. Each node contains a reference pointing to the left node and a reference pointing to the right node. Values smaller than items are stored in the left subtree, and values larger than items are stored in the right subtree. This tree also provides the add method to add a group of T-type values by using the parameter qualifier:

Public VoidAdd (ParamsT [] items );

This tree provides an ienumerable<T>Type. Inorder calls the private auxiliary recursive function scaninorder and passes the root node of the tree to scaninorder. Scaninorder is defined as follows:

Ienumerable scaninorder (node root );

It returns ienumerable<T>Type iterator implementation, which traverses Binary Trees in order. One thing to note for scaninorder is that it recursively traverses this binary tree, that is, it uses the foreach loop to access ienumerable returned from recursive calls.<T>. In order (In-In an iteration, each node first traverses the child tree on its left, then traverses the value of the node itself, and then traverses the child tree on the right. In this case, three yield return statements are required. To traverse the left-side subtree, scaninorder is returned in the ienumerable<T>Use the foreach loop. Once the foreach loop returns, all nodes in the left subtree have been traversed. Then, scaninorder generates the value passed to its node as the root of the iteration, and executes another recursive call in the foreach loop. This is in the Child tree on the right.

By using the attribute inorder, you can write the following foreach loop to traverse the entire tree:

binarytree = New binarytree ();
tree. add (
4 , 6 , 2 , 7 , 5 , 3 , 1 );

foreach ( int num in tree. inorder)
{< br> trace. writeline (Num);
}

//Traces 1, 2, 3, 4, 5, 6, 7

You can add other attributes to implement the pre-order in a similar way (pre
-Order and post-Order) iteration. Although the ability to use the iterator in recursion mode is obviously a powerful function, exercise caution when using it because it may cause serious performance problems. Each call to scaninorder requires instantiating the iterator generated by the compiler. Therefore, traversing a deep tree recursively may cause a large number of objects to be generated behind the scenes. In a symmetric binary tree, there are about N iterator instances, where N is the number of nodes in the tree. At any specific time point, about n of these objects are active. In a tree of an appropriate size, many such objects make the tree pass0) Garbage collection. That is to say, by using stacks or queues to maintain a column of nodes to be checked, the iterator can still easily traverse recursive data structures (such as trees ).

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.