C # anonymous functions and Delegation

Source: Internet
Author: User

In C # versions earlier than Version 2.0,Delegate DeclarationThe only way is to useNaming Method. C #2.0 introducedAnonymous MethodIn C #3.0 and later versions,LambdaExpressionReplaces the anonymous method as the preferred method for writing Inline code. However, the information about anonymous methods in this topic also applies to Lambda expressions. In one case, 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. For more information about lambda expressions, see MSDN


// Anonymous function var p1 = new {Name = "Zhang San", Age = 28}; var p2 = new {Name = "Li Si", Age = 29 }; var intArr = new [] {1, 2, 3, 4, 5 };

First, let's take a look at the above Code, which is relatively simple. It is basically the same as defining an instance, but there is no specific type after new; here, we use the new keyword to call the anonymous initiator to create an anonymous type object. The anonymous type is directly inherited from the System. objects. Anonymous members are the read/write attributes inferred by the compiler based on the initialization tool.

Here we note that C # anonymous functions are basically used with implicit var, and the order of definition must be noted, the attribute names, types, and sequences defined during the initialization of p1 and p2 are the same. Therefore, the compiler considers them to be of the same type and can use a value assignment statement such as p1 = p2. In particular, the order must be noted, if the names are of the same type and the order is different during initialization, p1 and p2 are of the two types. If p1 = p2 is used, an error will be thrown during compilation: the type "AnonymousType #1" cannot be implicitly converted to "AnonymousType #2 ". note that the initial value cannot be null when defining an anonymous function.


The following is an example.

1. bind an anonymous function to the Delegate

Use the anonymous method in the event


The following is an example of a timer.General naming conventionsAs follows:

class EventTest    {        public void Test()        {            System.Timers.Timer timersTimer =new System.Timers.Timer();             timersTimer.Enabled = true;            timersTimer.Interval = 5000;            timersTimer.Elapsed += newSystem.Timers.ElapsedEventHandler(timersTimer_Elapsed);            Console.ReadLine();        }         void timersTimer_Elapsed(object sender,System.Timers.ElapsedEventArgs e)        {           Console.WriteLine(System.DateTime.Now);        }    }

For event processing, we need to write a separate method timersTimer_Elapsed.Anonymous MethodTo save the definition of this method, as shown below:

class EventTest    {        public void Test()        {            System.Timers.Timer timersTimer =new System.Timers.Timer();             timersTimer.Enabled = true;            timersTimer.Interval = 5000;            timersTimer.Elapsed +=                delegate(object sender,System.Timers.ElapsedEventArgs e)                {                   Console.WriteLine(System.DateTime.Now);                };            Console.ReadLine();        }    }

That is, the implementation of the method is written in the internal.


2The anonymous method directly obtains the variable of the current caller.

Associate a delegate with an anonymous method. Associate a delegate with a naming method (DoWork.

Delegate void Printer (string s); class TestClass {static void Main () {// 1. associate a delegate with an anonymous method. printer p = delegate (string j) {System. console. writeLine (j);}; p ("The delegate using the anonymous method is called. "); // 2. associate a delegate with a naming method (DoWork. P = new Printer (TestClass. doWork); p ("The delegate using the named method is called. ");} static void DoWork (string k) {System. console. writeLine (k) ;}}/* Output: The delegate using the anonymous method is called. the delegate using the named method is called. */

Of course, although the Code looks few, the compiler will generate other methods during compilation. That is to say, the anonymous method can reduce the amount of code,

It saves development time, but does not improve the performance.


Conclusion: The instance realizes that the anonymous function can simplify the code, but this degree must be determined based on its own level. Otherwise, an error occurs.

Very difficult. Second, the compilation of anonymous functions does not simplify the amount of code, and a class and similar method will be generated in the background during the production. But if you want

Pass the Code as the delegate parameter, and create an anonymous method is the only method. NextLambda expressions




Related Article

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.