The anonymous method is the delegate

Source: Internet
Author: User

When two numbers are added, subtracted, multiplication, and division, one solution is implemented by delegation. As follows:

    class Program
    {
        private delegate int CaculateDel(int num1, int num2);
        static void Main(string[] args)
        {
            CaculateDel caculateDel = Add;
            Console.WriteLine(caculateDel.Invoke(1,2).ToString());
            Console.ReadKey();
        }
        static int Add(int num1, int num2)
        {
            return num1 + num2;
        }
    }

Above, the add method is assigned to the delegate variable of caculatedel type.

 

If you use the anonymous method, it is:

    class Program
    {
        private delegate int CaculateDel(int num1, int num2);
        static void Main(string[] args)
        {
            CaculateDel caculateDel = delegate(int num1, int num2)
            {
                return num1 + num2;
            };
            Console.WriteLine(caculateDel.Invoke(1,2).ToString());
            Console.ReadKey();
        }
    }   

 

It can be seen that the anonymous method is the delegate, and the anonymous method has better flexibility, so you do not need to write the method "dead" in advance ".

If we use system. the stopwatch instance method reset, start, and stop of diagnostics can be used to reset, start, and end stopwatch. The elapsedtickes attribute of stopwatch is used to display the time. We can find that the anonymous method is more efficient.

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.