Delegate, event, and lambda expressions in C #

Source: Internet
Author: User

The delegation, events, and lambda expressions in C # often make me dizzy. Today I will briefly summarize the content from chapter 13 and 14 of C # Getting Started classic.

Delegation is a typeYou can store references as function types.Is actually very simple. Define a delegate first, then declare a variable of the delegate type, and then initialize the variable as a reference to a function with the same return type and parameter list as the delegate. Then you can use the delegate variable to call the function, just as the variable is a function.

Anonymous method: it is not a traditional method, but created purely for the purpose of delegation. The format is as follows:

Delegate (parameters) {// anonymous method code}

Event: events are similar to exceptions because they are all thrown by objects, but the difference is whether to use a try-catch similar structure to process events, but subscribe is required) they subscribe to an event to provide the code that is executed when the event occurs. They are called event handlers. The requirements for the event handler must match the response types and parameters required by the event. These restrictions are part of the event definition and are specified by a delegate.

The process is as follows: the application creates an object that can trigger the event, the application subscribes to the event, and then notifies the event handler after the event occurs.

Main (Connection myConnection1 = myConnection1.name = Connection myConnection2 = myConnection2.name = Display myDisplay = myConnection1.MessageArrived + = myConnection2.MessageArrived + = name {; poolTimer = Timer (poolTimer. elapsed + = Random random = checkForMessage (Console. writeLine (random. next () =) & (MessageArrived! = MessageArrived (, MessageArrivedEventArgs (Console. WriteLine (Console. WriteLine (Message {MessageArrivedEventArgs () {message = MessageArrivedEventArgs (newmessage) {message =}View Code

Among them, the MessageHandler delegate contains two common parameters in the event handler: (object source, MessageArrivedEventArgs e); are: reference of the object that triggers the event, and parameters transmitted by the event.

Because delegation is difficult to use, you must first define the delegate, declare the delegate variable, and then initialize the variable as a reference to a function with the same return type and parameter list as the delegate, then, the delegate variable is used to call the function. Therefore, Microsoft defines a simple method, namely, the Action <T> delegate and the Func <T> delegate, which indicate that there are/no return values, respectively, the usage is as follows:

Main (name myname = myprint print1 = print1 (Action <String> print2 = print2 (myprint print3 = (String s) {Console. writeLine (, s) ;}; print3 (print1 () {Console. writeLine (print2 (String s) {Console. writeLine (}View Code

The three methods have the same effect.

Lambda expressions

I understand:Lambda expressions are essentially a delegate.It is used to simplify some aspects of C # programming. It consists of three parts: parameter list in brackets; => operator; C # statement. The compiler extracts this lambda expression and creates an anonymous method.

For example, the effect of the following statements is the same as that of the preceding three statements.

Action <String> newprint = (s) => {Console. WriteLine ("{0}", s );};

Note that some functions use the Action <T> delegate and Func <T> delegate as parameters, which is very convenient to use. For example, you can find the first person named "Jim" in the List:

Main (List <Employee> noEmployees = List <Employee> oneEmployeeList = List <Employee> Employee {ID =, Name =, salary = List <Employee> employees = List <Employee> Employee {ID =, Name =, Salary = Employee {ID =, Name =, Salary = Employee {ID =, Name =, salary = Employee {ID =, Name =, Salary = first = firstJim = employees. first (e => e. name. startsWith (firstJim1 = employees. first (Employee em) {em. name. startsWith (firstDoe = employees. first (e => e. name. endsWith (empty1 = noMatch1 = employees. firstOrDefault (e => e. ID = ID {; String Name {; Salary {;}View Code

This kind of syntactic sugar is really confusing, and it is similar to the four-way Writing of the word ". However, it is good to write concise and beautiful code after you are familiar with it.

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.