C # anonymous method

Source: Internet
Author: User

In C #1.1, the declaration and use of delegation requires that you have a delegate and a method that can be executed with a matching signature when the delegate is triggered, and an allocation statement that associates the naming method with the delegate.

Namespace anonymous method example {// <summary> // C #1. X delegate usage // </Summary> class program {// 1. declare the delegate sample delegate int sample (int x, int y); // 2. declare the method that matches the delegate sample signature plus static int plus (int x, int y) {return X + Y;} static void main (string [] ARGs) {// 3. associate the delegated sample with method plus with sample F = new sample (plus); int result = f (1, 2); console. writeline (result );}}}

In C #2.0, the new anonymous method is introduced, which allows developers to declare their own function code inline (Inline) without using a delegate function (delegate function ). The anonymous method basically saves the ability to provide the same features as the previous naming method, but it does not need to be explicitly created before it is associated with the delegate. When the compiler encounters an anonymous method, the compiler creates a naming method in the class and associates the method with the delegate. The differences between the implementation of anonymous methods and the implementation of naming methods are very small, and the performance difference is also very small.

Namespace anonymous method example {// <summary> // C #2.0 how to use the anonymous method /// </Summary> class program {// 1. declare the delegate sample delegate int sample (int x, int y); static void main (string [] ARGs) {// 2. use the anonymous method sample anonymousfunction = delegate (int x, int y) {return x + y ;}; int result = anonymousfunction (1, 2); console. writeline (result );}}}

Parameters in the anonymous method:

1. The anonymous method can accept real parameters, but does nothing:

Namespace anonymous method example {// <summary> // C #2.0 how to use the anonymous method /// </Summary> class program {// 1. declare the delegate sample delegate int sample (int x, int y); static void main (string [] ARGs) {// 2. use the anonymous method. The anonymous method accepts real parameters, but does not use sample anonymousfunction = delegate (int x, int y) {return Int. maxvalue ;}; int result = anonymousfunction (1, 2); console. writeline (result );}}}

2. The anonymous method ignores the parameter, although its corresponding delegate definition includes the parameter:

Namespace anonymous method example {// <summary> // C #2.0 how to use the anonymous method /// </Summary> class program {// 1. declare the delegate sample delegate int sample (int x, int y); static void main (string [] ARGs) {// 2. using the anonymous method, the anonymous method ignores the parameter, although its corresponding delegated sample is defined as the sample anonymousfunction = delegate {return int that contains the parameter. maxvalue ;}; int result = anonymousfunction (1, 2); console. writeline (result );}}}

Note: For anonymous method parameters, you can select either of the preceding two conditions, or ignore all parameters (the number of parameters is 0 and the number of ignored parameters is different. Treat them differently ), either the parameter format is the same as the delegate parameter format, or the compiler reports an error.

For example, the compiler reports an error in the following cases:

Namespace anonymous method example {// <summary> // C #2.0 how to use the anonymous method /// </Summary> class program {// 1. declare the delegate sample delegate int sample (int x, int y); static void main (string [] ARGs) {// 2. if you use an anonymous method or an anonymous method parameter, either ignore all the parameters or the parameter form is the same as that of the delegate parameter. Otherwise, the compiler reports the error sample anonymousfunction = delegate () {return Int. maxvalue ;}; sample anonymousfunction1 = delegate (int x) {return Int. maxvalue ;}; int result = anonymousfunction (1, 2); console. writeline (result );}}}

 

In addition, the anonymous method can also declare generic parameters <t>. An anonymous method with generic parameters can be assigned to a same type of delegate instance, so you only need to ensure that it complies with the delegate signature.

Namespace anonymous method example {// <summary> // C #2.0 how to use the anonymous method /// </Summary> class program {static void main (string [] ARGs) {testclass <string> C = new testclass <string> (); C. test ("123") ;}/// <summary> // anonymous method and generics /// </Summary> class testclass <t >{// 1. declare the delegate sample delegate void sample (T); Public void test (t) {// 2. the anonymous method can also declare generic parameters. An anonymous method with generic parameters can be assigned to a same type of delegate instance, you only need to ensure that it complies with the delegate signature to sample anonymousfunction = delegate (T Arg) {console. writeline (Arg. tostring () ;}; anonymousfunction (t );}}}

Return Value of the anonymous method:

1. If the return value type of the delegate type is void, no value can be returned in the anonymous method. In the preceding example of the Delegate and fan type, the return value is void.

2. If the return value type of the delegate type is not void, the return value of the anonymous method cannot be void, that is, it can be consistent with the return value of the delegate type. In the preceding example, the return value is int.

External variables of the anonymous method:

The anonymous method sometimes uses some local variables and parameters. These local variables and parameters are called"External variables of the anonymous method". The lifetime of the external variable is extended due to the capture benefit of the anonymous method until the delegated instance is not referenced.

Namespace anonymous method example {// <summary> // C #2.0 how to use the anonymous method /// </Summary> class program {// 1. declare the delegate sample delegate void sample (); static void main (string [] ARGs) {int test = 100; // 2. use the anonymous method. Use sample anonymousfunction = delegate {console for external parameters of the anonymous method. writeline (TEST); test = 200; console. writeline (TEST) ;}; console. writeline (TEST); console. writeline ("before invoke:" + Test); anonymousfunction. invoke (); console. writeline ("after invoke:" + Test); console. writeline (TEST); console. readkey ();}}}

Program output:

100
Before invoke: 100
100
200
After invoke: 200
200

 

Namespace anonymous method example {// <summary> // C #2.0 how to use the anonymous method /// </Summary> class program {// 1. declare the delegate sample delegate void sample (); static void function (INT test) {// 2. use the anonymous method. Use sample anonymousfunction = delegate {console for external parameters of the anonymous method. writeline (TEST); test = 200; console. writeline (TEST) ;}; console. writeline ("before invoke:" + Test); anonymousfunction. invoke (); console. writeline ("after invoke:" + Test);} static void main (string [] ARGs) {int test = 100; console. writeline (TEST); function (TEST); console. writeline (TEST); console. readkey ();}}}

Program output:

100
Before invoke: 100
100
200
After invoke: 200
100

The use of external variables by the anonymous method is not much different from that of normal local variables.

When to use the anonymous method:

1. A temporary method is required, which is rarely used;

2. The code for this method is very short and may even be shorter than the method declaration;

Note:

The anonymous method cannot access the ref or out parameters in the external range.

You cannot access any Insecure code in the "anonymous method block.

Anonymous methods are not allowed on the left side of the is operator.

In C #3.0, a new feature-Lambda expression is introduced, which provides a more general format to accomplish the same goal. However, the anonymous method provides functions not available in lambda expressions. You can use the anonymous method to ignore the parameter list. This means that the anonymous method can be converted to a delegate with various signatures. This is not possible for lambda expressions.

Namespace anonymous method example {// <summary> // C #3.0 Lambda expression usage // </Summary> class program {// 1. declare the delegate sample delegate int sample (int x, int y); static void main (string [] ARGs) {// 2. use the lambda expression sample plusdelegate = (x, y) =>{ return x + y ;}; int result = plusdelegate (1, 2); console. writeline (result );}}}

 

References:

Http://www.cnblogs.com/PolarLights/archive/2006/03/03/342416.html

Http://www.cnblogs.com/kid-li/archive/2006/12/12/589455.html

C # anonymous method

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.