. NET basic literacy-small example string delegate, anonymous method, Lamuda expression

Source: Internet
Author: User

I understand the delegate as: the delegate is the format of a method, and of course he is a type.

as long as the format of the method is the same as the format of the delegate definition, you can attach the method to the delegate. See Demo below

Declaring a delegate:

<p style= "margin:0in;font-family: Microsoft Jas Black; font-size:12.0pt" ></p><pre name= "code" class= "CSharp" > public delegate void Add (int a,int b);

Declare a method of the same format:

        static void Othermethod (int a, int b)        {            Console.WriteLine (a+b);        }

Declaring a member variable of a delegate type to a class

public class person    {public        string Name {set; get;}        public string Age {set; get;}        Public Add myadd;    }

Attach the method to the delegate, call it, and test the following:

Static Voidmain (string[] args) {person    P1 =new person ();    P1. Myadd = Othermethod;    P1. Myadd (7, 8);     Console.ReadLine ();}

Console output-- the

If we define the Othermethod infrequently, there is no need to declare a method separately. You can use anonymous methods, that is, when attaching a method to a delegate, it is possible to construct an anonymous method that is identical to the delegate format:

The wording is as follows:

P1. Myadd = Delegate (inta, int b) {Console.WriteLine (A + b);};

Anonymous methods, as the name implies, there is no method name, only the method parameters and methods of the algorithm, can be really simple enough.


Also, we can use it directly Lamuda expression, directly constructs a method, as follows :

P1. Myadd = (int a, int b) = = {Console.WriteLine (a + b);};

The advent of anonymous methods and lambda expressions makes writing methods easier.



. NET basic literacy-small example string delegate, anonymous method, Lamuda expression

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.