C # generic Delegate and lambda summary

Source: Internet
Author: User

Original link: http://www.xuebuyuan.com/456117.html

Named Method delegate

Class Mydelegatetest
{
        //step 1, declaring delegate object public
        delegate void MyDelegate (string name);
        This is the method we want to pass, and it has the same parameter and return value type as MyDelegate public
        static void Mydelegatemethod (string name)
        {
            Console.WriteLine ("Hello,{0}", name);
        }

        public static void Main ()
        {
            //step 2, create delegate object
            mydelegate md = new MyDelegate ( Mydelegatetest.mydelegatemethod);

            Step 3, call Delegate
            MD ("Michael");

            Console.ReadLine ();
        }
Anonymous method Delegate
Class Anonymousdelegate
{
        private delegate void MyDelegate (string name);
        public static void Main ()
        {
            MyDelegate mydelegate = Delegate (string name)
            {
                Console.WriteLine (name);
            };

           MyDelegate ("Michael");

           Console.ReadLine ();
        }



lambda expression
Lambda expressions are a new syntax for c#3.0, which provides a more concise, functional syntax for writing anonymous methods.

Class Lambdatest
{
        private delegate void MyDelegate (string name);
        public static void Main ()
        {
            //anonymous delegate
            mydelegate mydelegate = (name) => {Console.WriteLine (name); 

            //Call Delegate
            mydelegate ("Michael");

            Console.ReadLine ();
        }
Using lambda expressions is simpler and less concise. Actually, the compiler did a lot of things for us. MyDelegate mydelegate = (name) => {Console.WriteLine (name); The compiler will generate a private static method for us at compile time. You can see through the ILDASM.

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.