Analysis of improvement and realization principle of iterators in C # 2.0
Source: Internet
Author: User
The C # language absorbs a very practical foreach statement from VB. For all instances of classes that support the IEnumerable interface, the foreach statement iterates through its subkeys using a unified interface, making the tedious bookkeeping of the previously lengthy for loop completely automated by the compiler. Classes that support the IEnumerable interface typically implement the IEnumerator interface with an inline class and, through the Ienumerable.getenumerator function, allow the user of the class to complete traversal work such as the foreach statement.
This feature is very convenient to use, but it will pay a price. Juval Lowy published in MSDN Magazine in the 5th issue of 2004, create elegant Code with Anonymous Methods, iterators, and Partial classes, described in more detail the C # 2.0 Iterative support and other new features in.
First, because the IEnumerator.Current property is a value of type object, each value must undergo a useless box and unbox operation when it is traversed by a foreach statement, which is a reference type ( Reference type), when used by a foreach statement, a redundant castclass instruction is also required to guarantee the correctness of the type conversion of the enumerated values.
The following are references:
Using System.Collections;
public class Tokens:ienumerable
{
...
Tokens F = new tokens (...);
Console.WriteLine (item);
} while (enum. MoveNext ());
}
Finally
{
if (enum is IDisposable)//need to verify that the class that implements the IEnumerator interface supports the IDisposable interface
{
((IDisposable) enum). Dispose ();
}
}
Fortunately, the concept of generics (generic) is supported in C # 2.0, and a strongly typed generic version IEnumerable definition is provided, pseudocode as follows:
In this way, it guarantees the type safety of traversing the collection, and can directly operate the actual type of the set, avoid redundant conversion and improve the efficiency.
The following are references:
Using System.Collections.Generic;
public class Tokens:ienumerable<string>
{
...//Implement Ienumerable<string> interface
Tokens F = new tokens (...);
foreach (string item in F)
{
Console.WriteLine (item);
}
}
The code above is automatically converted to
The following are references:
Tokens F = new tokens (...);
ienumerator<string> enum = F.getenumerator ();
Try
{
do {
String item = Enum.get_current (); No conversion required
Console.WriteLine (item);
} while (enum. MoveNext ());
}
Finally
{
if (enum)///without verifying that the class that implements the IEnumerator interface supports the IDisposable interface,
Because all the IEnumerator interface implementation classes that are automatically generated by the compiler support
{
((IDisposable) enum). Dispose ();
}
}
In addition to the reduced performance of redundant conversions while traversing, another problem with C # 's existing version is that implementing the IEnumerator interface is too cumbersome. Typically, a IEnumerator interface is implemented by an inline class, and this inline class, except the Get_current () function, is essentially the same as the other parts of the function, such as
The following are references:
public class Tokens:ienumerable
{
public string[] elements;
Tokens (string source, char[] delimiters)
{
Parse the string into tokens:
elements = source. Split (delimiters);
}
Public IEnumerator GetEnumerator ()
{
Return to New Tokenenumerator (this);
}
Inner class implements IEnumerator interface:
Private Class Tokenenumerator:ienumerator
{
private int position =-1;
Private tokens t;
Public tokenenumerator (Tokens t)
{
THIS.T = t;
}
Declare the MoveNext method required by IEnumerator:
public bool MoveNext ()
{
if (Position < t.elements.length-1)
{
position++;
return true;
}
Else
{
return false;
}
}
Declare the Reset method required by IEnumerator:
public void Reset ()
{
Position =-1;
}
Declare the required by IEnumerator:
public Object Current
{
Get//Get_current function
{
return t.elements[position];
}
}
}
...
}
The position and tokens of the inline class tokenenumerator are actually common to every class that implements the IEnumerator interface, except that the get function of the current property is different. In this regard, C # 2.0 has made great improvements, adding support for the yield keyword, and allowing code to be reused logically. The lengthy code above requires only a few lines in C # 2.0, such as
The following are references:
Using System.Collections.Generic;
public class Tokens:ienumerable<string>
{
Public ienumerator<string> GetEnumerator ()
{
for (int i = 0; i<elements. Length; i++)
Yield elements[i];
}
...
}
The GetEnumerator function is a C # 2.0-supported iteration block (iterator blocks) that tells the compiler when to return what value by yield, and then the compiler completes the implementation automatically ienumerator<string> The thin record of the interface works. The yield break statement supports a direct end from an iteration block, as
The following are references:
Public ienumerator<int> GetEnumerator ()
{
for (int i = 1;i< 5;i++)
{
yield return i;
if (i > 2)
Yield break; i > 2 o'clock End traversal
}
}
This makes it easy to implement the IEnumerator interface and can easily support multiple enumeration methods in a class, such as
The following are references:
public class Citycollection
{
String[] m_cities = {"New York", "Paris", "London"};
Public ienumerable<string> Reverse
{
Get
{
for (int i=m_cities.length-1; i>= 0; i--)
Yield m_cities[i];
}
}
}
Next, let's look at what the compiler does for us behind the language features that are so handy. Take the Tokens class, which supports the Ienumerable<string> interface above, for example, the code for the GetEnumerator function is compiled using a class wrapper, pseudocode as follows
The following are references:
public class Tokens:ienumerable<string>
{
Private Sealed class Getenumerator$00000000__ienumeratorimpl
: Ienumerator<string>, IEnumerator, IDisposable
{
private int $PC = 0;
private string $_current;
Private Tokens <this>;
public int i$00000001 = 0;
Public ienumerator<string> GetEnumerator ()
{
Getenumerator$00000000__ienumeratorimpl impl = new Getenumerator$00000000__ienumeratorimpl ();
Impl.<this> = this;
return impl;
}
}
From the pseudocode above, we can see that the C # 2.0 compiler actually maintains an inner class that is very similar to the Tokenenumerator class that we implemented IEnumerator interface in front of us to encapsulate ienumerator<string> The implementation of the interface. The implementation logic of this embedded class is determined according to the yield return location defined by GetEnumerator.
Let's look at the implementation of a more complex iteration block, which supports recursive iterations (recursive iterations), and the code is as follows:
The following are references:
Using System;
Using System.Collections.Generic;
Class node<t>
{
Public node<t> Leftnode;
Public node<t> Rightnode;
Public T Item;
}
public class Binarytree<t>
{
Node<t> M_root;
public void Add (params t[] items)
{
foreach (T item in items)
ADD (item);
}
public void Add (T item)
{
// ...
}
Public ienumerable<t> Inorder
{
Get
{
return ScanInOrder (M_root);
}
}
if (root. Rightnode!= null)
{
foreach (T item in ScanInOrder (root). Rightnode))
{
Yield item;
}
}
}
}
Binarytree<t> provides a inorder property that supports the Ienumerable<t> interface, traversing the entire binary tree through the ScanInOrder function. Because implementing the Ienumerable<t> interface is not the class itself, but a property, the compiler first generates an inline class to support the Ienumerable<t> interface. Pseudo code is as follows
The following are references:
public class Binarytree<t>
{
Private Sealed class Scaninorder$00000000__ienumeratorimpl<t>
: Ienumerator<t>, IEnumerator, IDisposable
{
Binarytree<t> <this>;
Node<t> Root;
Because the content of the ScanInOrder function needs to use the root parameter, the wrapper class for the ienumerable<t> and ienumerator<t> interfaces needs to have a root field to hold the parameters of the incoming ScanInOrder function. and pass it to the final implementation function.
The implementation principle of the embedded wrapper class scaninorder$00000000__ienumeratorimpl<t> implementing the Ienumerator<t> interface is similar to that in the previous example, and the difference is that the program logic is greatly complicated, and need to use the IDisposable interface to complete the collection of resources.
The following are references:
public class Binarytree<t>
{
Private Sealed class Getenumerator$00000000__ienumeratorimpl
: Ienumerator<t>, IEnumerator, IDisposable
{
private int $PC = 0;
private string $_current;
Private Tokens <this>;
public int i$00000001 = 0;
Public ienumerator<t> __wrap$00000003;
Public ienumerator<t> __wrap$00000004;
Public T item$00000001;
Public T item$00000002;
public node<t> root;
By using the pseudocode above, we can see that C # 2.0 is actually a recursive iteration block that is accomplished by a finite state machine with $pc as a variable, possibly because the finite state machine can be easily generated automatically by the program. The Dispose () function is responsible for processing the intermediate variables of the state machine.
Friends who are interested in further understanding the iteration feature can read iterators related articles on the blog of Grant Ri.
After understanding the principle of iterators, the discussion will not be fooled by its appearance:D
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