Understand anonymous methods (anonymous method) in C #2.0)

Source: Internet
Author: User
Anonymous methods is one of the new features of C #2.0, which allows us Code Create a built-in method without a method name and associate the Code with the delegated instance. This makes the delegation instantiation more intuitive and convenient, and improves the readability and maintainability of the Code. The following describes how to use a simple anonymous method:

Private   Int [] _ Integers = {1,2,3,4,5,6,7,8,9,10} ;

Int [] Evenintegers = Array. findall (_ integers, Delegate ( Int Integer)
{
Return(Integer%2 = 0);
}
);

The code above uses the anonymous method to obtain the number of divisible by 2 in the array. The anonymous method is:

Delegate ( Int Integer)
{
Return(Integer%2 = 0);
}

If we do not need anonymous methods, we need to create a specific method, as shown below:

Private   Int [] _ Integers =   {1,2,3,4,5,6,7,8,9,10} ;

Int [] Evenintegers = Array. findall (_ integers, iseven );

Private   Bool Iseven ( Int Integer)
{
Return(Integer%2 = 0);
}

The anonymous method is used in the case that the method is relatively simple and will not be called elsewhere. We can also use the anonymous method as follows:

Button1.click + =

Delegate
{
MessageBox. Show ("Hello");
} ;

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.