A preliminary understanding of C # Learning delegates, events, anonymous methods, and lambda

Source: Internet
Author: User

Learn Linqtosql, then drag the lambda expression, then pull the anonymous method, then pull the delegate, and finally pull the event processing ... It was later discovered that the process of delegating this concept and event processing was not very clear, so we had to learn the notes. That's not right, please give us a lot of advice!

The first part: Understanding the delegation

Entrustment, as the name implies, is similar to the meaning of intermediaries, some things you do not, entrust others to do, such as you want to blind date, but you do not want to go to the initiative about the girl, then you can give matchmaker to help you about.

If you have learned C + +, please interpret the delegate as a function pointer in order to invoke the function. A function pointer can call a function that conforms to the function pointer requirements. What does it mean to meet the function pointer requirements? The called function has the same return type as the function pointer, has the same number of arguments, and corresponds to the type of the corresponding parameter.

int ( * p) (int,int); defines a function pointer p,p can only call a function prototype (or function signature) is a return type of int, There are only two parameters and the parameter types are functions of int.

< Span style= "color: #000000; font-size:14px; " > Delegate example Description: Delegate void MyDelegate (int a,int b); declared A delegate type mydelegate (there are different types of delegates, as if there are different types of intermediaries, you want to blind date to find matchmaker such intermediary, you want to see Feng shui, you find the master of Feng Shui), this delegate type can only call the return type is void, only two parameters and the parameter type is an int function. Does it look like a function pointer?

The delegate is actually a class, the base class of the delegate is the Delegate class, but we can not display the delegate class from the Delegate class (theDelegate class is not a delegate type, its derived class is), which is for the system and compiler. Only after the class instantiation is called the object, and after the delegate instantiation is called the delegate, in addition the instantiation delegate must provide a corresponding function as a parameter.

Example of defining a delegate: (Reference from: http://www.cnblogs.com/warensoft/archive/2010/03/19/1689806.html)

1. Define a function max, function signature bit: The return type is int, two parameters, the parameter type is int

int Max (int x,int y) {return x>y?x:y; }

2. Create a delegate type (name is MyDelegate) and declare the function prototype (function signature) of the function that the delegate type can call: The return type is int, two parameters, and the parameter type is int. Note that the delegate is a class that creates a delegate type to be placed outside the function

delegate int mydelegate (int a,int b);

3. Create an instance of a delegate class (or an instance of MyDelegate) and point to the method to invoke, in two ways:

This is the most common way of specifying the constructor method of a delegate class .

MyDelegate MD = new MyDelegate (MAX);

// Use automatic inference to indicate the method to invoke, which is more type than the function pointer

MyDelegate MD = Max;

When you create a delegate instance in the first way, you must provide a function signature that conforms to the delegate type as a parameter.

4, using the delegate class instance to invoke the method pointed to

int C = MD (4,5);

Summary: You can interpret a delegate as a function pointer, and you can call function signatures and delegate-type-consistent functions

The second part: Event processing (This article mainly wants to express the understanding of the delegation, so this part of the detailed later said)

Event handling involves two objects: one is the event source (the object that triggered the event) and the other is the event receiver (the class that provides the processing method). There is no connection between the two.

The process of event handling: The event source is the first to trigger an event, the delegate captures it (the delegate is implemented by subscribing to the event), and the delegate invokes the corresponding function in the event receive class for processing.

Example Description: This.button1.Click + = new System.EventHandler (this.button1_click);

The event source is button1, the event that is triggered is a button click event, and the delegate is System.EventHandler, and the event handler is button1_click. The above code means that System.EventHandler (delegate) subscribes to the Click (event) of the This.button1 (event source), and when the click event of the this.button1 occurs, the delegate receives some arguments passed by the event source, and then calls This.button1_click (event handler) and passes the arguments received from the event source to the function as arguments.

Part III: Anonymous Methods

Anonymous methods are methods that do not have a name (function), since there is no name, that is, only in the definition of the time can be called, in other places can not be called (No name Ah, then can not find it). Why use anonymous methods? Calling a function is a cost, but sometimes the methods that are called are short (such as a Word method), and only a few functions are done, which is a bit of a loss at this point in time, you can define an anonymous method to do this, and the anonymous method as inline code, the cost is relatively small. Anonymous methods are used in conjunction with delegates (and later lambda expressions), and you need to pass a function name to it as a parameter before you create a delegate instance, and you can now pass a piece of code directly through an anonymous method.

Define anonymous methods : Use the delegate keyword, such as:delegate (int a, int b) {return a > B? a:b;} The code defines an anonymous method with arguments of int A and int B, and the method body is {return a > b? a:b}. It makes no sense to just define an anonymous method, because you can no longer use the anonymous method after the definition, so the anonymous method should be used immediately when it is defined. In general, it is the initialization of a delegate.

Use anonymous methods:

1Namespace DelegateTest
2 {
3Class Program
4 {
5//To create a delegate type
6Delegateint MyDelegate (int x,int y);
7Staticvoid Main (String[] args)
: 9
9// Create delegate instance, point to anonymous function
Span style= "color: #008080;" >10 mydelegate mydelegate = delegate (int X,int y) {return x + y;};
11
12 //
13 Console.WriteLine (MyDelegate ( Span style= "color: #800080;" >3,2));
14
15 Console.readkey ();
16}
17}
18}

Summary: An anonymous method is a method that has no name and can only be invoked through a delegate (which may be wrong, an anonymous method can also subscribe directly to an event as an event handler, receive the corresponding parameter and execute the function body when the event occurs).

Part IV: LAMBDA

It says that delegates can be implemented anonymously by way of inline code, but there is a more concise way to use lambda expressions instead of anonymous methods, where lambda expressions are simple versions of anonymous methods.

the syntax for a LAMBDA expression is as follows:

(param1, param2 ..., paramn) =

{

Expression 1;

Expression 2;

return value;

}

param1, param2 ..., Paramn is the argument, not the type, the compiler will do the work, curly braces is the lambda expression to execute the statement, if the corresponding delegate type has a return value, then there will be a return statement.

Change the example of the anonymous method in part three to implement it with a lambda expression:

1Namespace DelegateTest
2 {
3Class Program
4 {
5//To create a delegate type
6Delegateint MyDelegate (int x,int y);
7Staticvoid Main (String[] args)
: 9
9//Create delegate instance, point to anonymous function
10//MyDelegate mydelegate = delegate (int x,int y) {return x + y;};

12 // Call the anonymous method via delegate
13 / / Console.WriteLine (MyDelegate (3,2));
14
15 MyDelegate youdelegate = (x, y) = = {return (x-y);};
16 Console.WriteLine (youdelegate (3, 2));
17
18 Console.readkey ();
19}
20}
21}

Summary: An anonymous method is a function without a name, a lambda expression is a concise version of an anonymous method (referring to the use of a delegate, Lambda has other uses), both to make the code more concise, but at the bottom level of the essence is the same

A preliminary understanding of C # Learning delegates, events, anonymous methods, and lambda

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.