2nd: anonymous method and iterator

Source: Internet
Author: User

2005.8.24 Li Jianzhong

Agenda

Use the anonymous method

Anonymous method Mechanism

Use iterator

Iterator Mechanism

Lecture Summary

 

Origins of anonymous methods

When no anonymous method is available (C #1.0)

With the anonymous method (C #2.0)

The delegate expresses a piece of code. After the anonymous method is introduced, the bridge method is removed to directly associate the delegate with the code. Although it does not have the new Keyword, it still performs the delegate instantiation, And the compiler will automatically add a specific method for us.

Its syntax is to useDelegateKeyword, followed by parentheses in the code block, so that the method does not need a name. If no parameter is used, you can leave the parameter of the method unspecified. This anonymous method is a simplified syntax and is applicable to the method that uses only once.

Introduction to anonymous methods

The anonymous method allows us to write method code in an "inline" way, directly associating the Code with the delegated instance, so that the work of delegated instantiation is more intuitive and convenient.

Several questions about the anonymous method:

-Parameter list

-Return Value

-External variables

 

Parameters of the anonymous method

The anonymous method can be followed by a parameter list (you can leave it unspecified) by the delegate keyword, and the subsequent code blocks can access these parameters;

Note the difference between "No parameter list specified" and "parameter list blank"

 

Return Value of the anonymous method

If the return value type of the delegate type is void, no value can be returned in the anonymous method;

If the return value type of the delegate type is not void, the value returned by the anonymous method must be compatible with the return value of the delegate type:

Here, the first return value type of the method is void. You can leave it empty.

 

External variables of the anonymous method

Some local variables and parameters may be used by anonymous methods. They are called "external variables of anonymous methods ".

The lifetime of the external variable isBenefits of anonymous methodsAnd extended until the delegated instance is not referenced.

The anonymous method is not a method. It is just a delegate instance. If the anonymous method is not called, the code in it will not be executed. If we output the value of the factor parameter after Invoke, the value of the factor will not change. If we call the anonymous method f n times, the value of factor will increase by 0.2 * n. This is because the factor is caught by the anonymous method and can be accessed within the anonymous method, so that the survival of the external variable is prolonged.

Delegation type inference

C #2.0 allows us to omit the delegate type when instantiating the delegate, and directly use the method name. The C # compiler will make reasonable inferences.

C # practices in 1.0

C # practices in 2.0

If the delegate type is omitted here, you must write only the method name, instead of the brackets and parameters. If you write the brackets, the method is called again. Only the method name indicates the entry point address of the incoming method, that is, the method pointer.

The simplification of these syntaxes is what the compiler does silently, which provides convenience for our work. However, there is no change in the runtime and there is no Optimization on the performance.

 

Anonymous method Mechanism

In C #2.0, the anonymous method only simplifies the task of delegation instantiation through the additional processing of the compiler. It has no fundamental difference with C #1.0 code.

Through the ildasm.exe Disassembly tool, we can gain an in-depth understanding of the anonymous method:

-Anonymous methods in static methods

-Anonymous methods in instance methods

-External variables in the anonymous method

 

Anonymous methods in static methods

The above code is converted:

Because F is a static method, the compiler will infer that Method1 is also a static method. The name generated by the compiler is certainly not Method1, but a confusing name that we do not want to call.

Anonymous method in instance method

The above code is converted:

Because the F method is an instance method, Method1 will also be created as an instance method by the compiler.

 

External variables in anonymous methods

The above code is converted:

The compiler first creates an instance class Temp, which contains the instance method Method1 and field y. F will first create a new Temp type when using the method, then pass the y value to the Temp instance and call the Method1 method. This is already the most elegant solution. The lifecycle of y is entrusted to be dragged and forced to be extended. As long as the reference of y is not lost, it will not be destroyed. In the past, we thought that on the stack, y has now become in the managed stack, with a relatively higher cost and lower performance. In addition, the anonymous method may change external variables and cause code confusion. Therefore, if not,Do not use external variables of the anonymous method on a large scale.

 

C # foreach in 1.0

When there is no iterator, create a set that can be used for foreach (C #1.0 ):

Use the foreach statement for the set: (col is the instance variable of MyCollection)

Equivalent:

 

Iterator in C #2.0

Use the iterator to create a set for foreach (C #2.0 ):

We only need to implement the GetEnumerator method and return the IEnumerator interface or generic interface. Method implementationYield returnImplementation, which is the implementation method of the iterator. This keyword is actually used to return the traversal of an element at a time, and implements the 1.0 implementation method within it.

Use the foreach statement:

Use the iterator to create reverse traversal:

Use yield return to generate enumeration elements:

Use yield break to interrupt iteration:

The concept of yield break is different from that of return in a loop. Yield break is equivalent to making MoveNext return value false to end iteration. If the yield break method is not used, the iterator sets MoveNext to false after all elements are iterated to end the iteration.

 

Iterator Mechanism

The iterator in C #2.0 also simplifies the creation of enumeration sets that can be used for foreach through an additional processing by the compiler.

Through the ildasm.exe Disassembly tool, we can gain an in-depth understanding of the iterator:

-GetEnumerator () method in the iterator

-Nested classes in the iterator

-Yield statement in the iterator

 

Code demo-use ILDasm to analyze the iterator Mechanism

Yield return is not a normal return, but a return for each element.

The IL Code shows that the compiler has automatically generated an internal class for us and implemented the IEnumerator interface (generic and non-generic). It maintains a state machine internally, continuously traverse the elements in the set.

 

Lecture Summary

The anonymous method allows us to directly associate code with the delegated instance in an "inline" way, making the task of delegation instantiation more intuitive and convenient. The iterator allows us to easily compile an enumeration set applied to the foreach statement.

For advanced languages like C #, it is very important to master what the compiler has done for us. Both the anonymous method and iterator in C #2.0 simplify the programmer's work by doing some additional processing at the compilation level.

2010.10.29

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.