Anonymous method, c # anonymous method

Source: Internet
Author: User

Anonymous method, c # anonymous method
Anonymous Method

In versions earlier than C #2.0, the only way to create a delegate is to use the naming method. Anonymous methods have been introduced since C #2.0. in C #3.0 and later versions, Lambda expressions replace anonymous methods, and thus serve as the preferred method for writing Inline code. However, the information about anonymous methods here also applies to Lambda expressions. Note that the anonymous method provides functions not available in Lambda expressions. That is, you can ignore the parameter list using the anonymous method. This means that the anonymous method can be converted to a delegate with various signatures. This is almost impossible for Lambda expressions. For more information about lambda expressions, let's talk about it next time.

To pass a code block as a delegate parameter, creating an anonymous method is the only method.

Example 1:

// Create a Click event button1.Click + = delegate (Object o, EventArgs e) {MessageBox. Show ("Click! ");};

 

Example 2:

// Create a delegate. delegate void MyDel (int x); // use the anonymous method to instantiate the delegate MyDel d = delegate (int k ){/*...*/};

 

By using the anonymous method, you do not need to create a separate method, which reduces the coding system overhead required for instantiating the delegate.

For example, if the system overhead required to create a method is unnecessary, it may be useful to specify a code block (rather than a delegate. This example of starting a new thread is a good example. Without creating more methods for the delegate, the thread class can create a thread and contain the code executed by the thread.

    void StartThread()    {        Thread t1 = new Thread          (delegate()                {                    Write("Hello, ");                    WriteLine("World!");                });
t1.Start(); }

 

Features

The parameter range of the anonymous method is"Anonymous method Block".

If the target is outside the block, it is wrong to use Jump statements (such as goto, break, or continue) in the anonymous method block. If the target is inside the block, use the jump statement outside the anonymous method block (for examplegoto,breakOrcontinue) Is also incorrect.

If the range of local variables and parameters already contains anonymous method declarations, the local variables and parameters are called the"External"Variable. For examplenIs an external variable:

        int n = 0;        MyDel d = delegate() { WriteLine("#:{0}", ++n); };

  

Reference of external variablesN, SetIt is considered to be performed when a delegate is createdCaptureDifferent from the local variable, the captured variable will survive in the lifetime and reference this anonymous method to be delegated to be spam.

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

In theAnonymous method Block.

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

 

Delegation example

The following example demonstrates how to instantiate a delegate. Both methods will display a message when calling the delegate:

  • Associate a delegate with an anonymous method.

  • Delegate and naming methods (DoWork) Association.

// Declare the delegate void Printer (string s); class MyClass {static void Main () {// use the anonymous method to instantiate the delegate Printer p = delegate (string j) {WriteLine (j) ;}; // returns the result p ("Call the delegate using an anonymous method. "); // Use the delegate instantiation of the method named" Do. P = new Printer (TestClass. Do); // use the old style to call the delegate p ("Use the naming method to call the delegate. ") ;}// Subsequently used to delegate the call to static void Do (string msg) {WriteLine (msg );}}

 

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.