C # Delegate,

Source: Internet
Author: User

C # Delegate,

C # graphic tutorial, version 4, chapter 2, delegation, learning notes

 

It can be considered that the delegate is an object that holds one or more methods.

However, unlike a typical object, a delegate can execute the delegate. In this case, the Delegate will execute the method it holds.

 

A delegate is a user-defined type like a class.

The class represents a collection of data and methods, while the delegate holds one or more methods and a series of predefined operations.

 

Follow these steps to use delegation,

1. Declare a delegate type. The delegate statement looks similar to the method, but does not implement blocks.

Delegate void MyDel (int value );

② Use this delegate type to declare a delegate variable.

MyDel del;

③ Create an object of the delegate type and assign it to a variable. The new delegate object includes reference to a method. This method is consistent with the signature and return type of the delegate type defined in step 1.

Del = new MyDel (class. method );

④ You can add other methods to the delegate object. These methods must be consistent with the signature of the delegate type defined in step 1 and the return type.

⑤ Call a delegate like a method. When a delegate is called, every method contained in the delegate is executed.

Del (int type variable );

 

You can regard delegate as an object that contains the list of ordered methods. These methods have the same signature and return type.

The list of methods is called the call list.

The method of saving the delegate can come from any class or structure, as long as its return type and signature include ref and out are consistent with the delegate type.

The method in the call list can be an instance method or a static method.

When a delegate is called, all methods in its call list are executed.

 

 

Declare delegate type

 

Delegate void MyDel (int x)

Keyword return type delegate type name Signature

 

The return type and signature specify the form of methods accepted by the delegate.

The delegate type declaration looks very similar to the method declaration, but there are two differences.

The delegate type declaration starts with the delegate keyword and has no method subject.

 

Create delegate object

 

MyDel delvar

Delegate Type Variable

 

There are two ways to create a delegate object

The first is to create an expression for an object using the new operator.

Delvar = new MyDel (class. Method)

The second type is

Delvar = Class. Method

This shortcut syntax is used because there is implicit conversion between the method name and its relative delegate type.

 

Assign a value to the Delegate

 

A delegate is a reference type. You can assign a value to it to change the reference contained in the delegate variable. The old object will be recycled by the garbage collector.

Delvar = Class 1. method;

Delvar = Class 2. method;

 

Combined Delegation

 

The delegate can use additional operators to "combine ". This operation will eventually create a new delegate, whose call list is connected to the call list copies of the two delegates that serve as the operands.

MyDel delA = Class. method;

MyDel delB = Class. method;

MyDel delA = delA + delC;

Although the composite delegate makes us feel like the operand delegate has been modified, they have not been modified. In fact, the delegate is constant and cannot be changed after the delegate object is created.

C3 provides the syntax that seems to be able to add methods to the delegate, that is, the + = Operator.

MyDel delvar = Class. method;

Delvar + = Class. method;

Delvar + = Class. method;

Of course, when the + = Operator is used, a new delegate is actually created.

 

Remove Method from delegate

 

We can also use-= to remove the delegate, but pay attention to the following points.

① If a method in the call list has multiple instances,-= will start searching from the end and remove the first instance that matches the method.

② It will be ineffective to try to delete methods that do not exist in the delegate.

③ An exception will occur when attempting to call an empty delegate. You can use null to determine whether the delegate is empty.

 

Call delegate

 

MyDel delvar = Class. method;

Delvar + = Class. method;

Delvar + = Class. method;

...

Delvar (value of the input method );

 

Call a delegate with a return value

 

If the delegate has a return value and has more than one method in the call list, the following occurs:

① The value returned by the last method in the call list is the value returned by the delegate call.

② Values returned by all other methods in the call list are ignored.

 

Call a delegate with reference parameters

 

If the delegate has a reference parameter, the parameter value is changed based on the return values of one or more methods in the call list.

When you call the next method in the delegate list, the new value (not the initial value) of the parameter is passed to the next method.

 

Anonymous Method

 

The anonymous method allows us to avoid using an independent named method.

The anonymous method is used to declare a connection during the initialization of the delegate.

That is, you do not need to call methods in a class in step 3 at the beginning.

MyDel delvar = delegate (int x) {return x + 20 ;};

The type of the returned data must be the same as that of the delegate type.

In addition to array parameters, the parameter list of the anonymous method must match the delegate in the following three aspects:

① Number of parameters ② parameter type and position ③ modifier.

You can omit the square brackets or leave the square brackets empty to simplify the parameter list of the anonymous method. However, two conditions must be met:

① The delegated parameter list does not contain the out parameter ② the anonymous method does not use any parameters.

 

Lambda expressions

 

C #2.0 introduces the anonymous method, and C #3.0 introduces the Lambda expression, which simplifies the syntax of the anonymous syntax.

In the syntax of the anonymous method, the delegate keyword is a bit redundant, because the compiler already knows that we are assigning a value to the delegate of the method,

To convert an anonymous method to a Lambda expression, follow these steps:

① Delete the delegate keyword

② Add Lambda operator => to the parameter list and anonymous method, and read the Lambda operator as goes.

MyDel del = delegate (int x) {return x + 1 ;};

MyDel del = (int x) =>{ return x + 1 ;};

However, this only saves 6 characters. However, the compiler can infer that we can further simplify it.

 

The compiler can know the type of the delegate parameter from the delegate Declaration, so the Lambda expression allows us to omit the type parameter:

MyDel del = (x) =>{ return x + 1 ;};

If there is only one implicit type parameter (the parameter list of the omitted type), we can omit the parentheses.

MyDel del = x =>{ return x + 1 ;};

Finally, Lambda expressions allow the body of expressions to be statement blocks or expressions.

If the statement contains a return statement, we can replace the statement block with the expression after the return keyword.

MyDel del = x => x + 1;

 

The main points about the Lambda expression parameter list are as follows:

① The parameters in the Lambda expression parameter list must match the number, type, and position of the parameters with the delegate.

② The parameters in the parameter list of the expression do not necessarily need to contain the type. Unless the ref or out parameter is delegated, the type must be specified.

③ If there is only one parameter and it is of the implicit type, parentheses can be omitted. Otherwise, parentheses must exist.

④ If there is no parameter, a set of empty parentheses must be used.

 

What is the use of delegation: http://bbs.csdn.net/topics/390751609/

Wonderful use of delegation and events: http://blog.csdn.net/susan19890313/article/details/6949738

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.