[C # Foundation] Delegate

Source: Internet
Author: User

What is a delegate

A delegate is a class that defines a method's type so that it can be passed as a parameter to another method, which dynamically assigns the method to the parameter, avoids the large use of the If-else (Switch) statement in the program, and makes the program more extensible.

Using delegates, you can bind multiple methods to the same delegate variable, and when you call this variable (the word "call" is used here because the variable represents a method), you can call all the bound methods in turn.

Definition of a delegate

Typically a delegate is defined as

 Public Delegate void Calcdelegate (intint y);

The keyword delegate is used to declare a delegate type Calcdelegate, you can add an access modifier to it, the default return type is void, accept two int parameter x and y, but the delegate is not equal to the method, but is a reference type.

Here's how to implement a calculator simulator with a delegate.

        //declaring a delegate         Public Delegate voidCalcdelegate (intXinty); //Create a method associated with a delegate that has the same return value type and argument list         Public Static voidADD (intXinty) {Console.WriteLine (x+y); }        //defining delegate type variables        Private Staticcalcdelegate MyDelegate; Static voidMain (string[] args) {           //to make a delegate bindingMyDelegate =Newcalcdelegate (ADD); //Callback Add MethodMyDelegate (1,2); }

In the example above, a calcdelegate delegate type is declared inside a class that has the exact same return value type and parameter list as the associated method add, otherwise it will result in a compilation error. Passing the method add to the Calcdelegate constructor, that is, assigning the method add to the Calcdelegate delegate and assigning the reference to the MyDelegate variable, also means that the mydelegate variable holds a reference to the Add method to implement the add The callback.

Thus, the delegate represents the signature of its callback method, which can be passed as a parameter and dynamically change the invocation of the method according to the method passed in. You can bind to a delegate as long as you provide a method with the same signature for the delegate.

For example:

        Public Static voidSubtract (intXinty) {Console.WriteLine (x-y); }Static voidMain (string[] args) {           //to make a delegate bindingMyDelegate =Newcalcdelegate (Subtract); //Callback Add MethodMyDelegate (1,2); }
Multicast delegation and delegation chain

In the above-mentioned delegate implementation, the Add method and the Subtract method can be bound to the same delegate type MyDelegate, so you can think of binding multiple methods to a delegate variable, and when you call a method, you can sequentially execute all the methods of its binding, which is called a multicast delegate.

In. NET with the + = and-= operators to bind and unbind separately, multiple methods bind to a delegate variable to form a chain of delegates, which, in turn, invokes all the bound callback methods.

For example:

Static void Main (string[] args)        {           // Delegate binding            new  calcdelegate ( ADD);             New calcdelegate (Subtract);             // callback Method            MyDelegate (12);        }

The above execution will output 3 and 1 in the console sequentially, and the visible multicast delegate invokes all the bindings in the order of the delegate chain, as well as the-= operation to unbind the delegate chain.

In fact, + = and-= respectively call the Delegate.combine and Delegate.remove methods

So the above example is equivalent to:

       staticvoid Main (string[] args)        {            // Delegate binding            mydelegate = (calcdelegate) delegate.combine (newnew  calcdelegate (Subtract));            MyDelegate (12);        }

The multicast delegate returns the execution result of the last call method, so it is not recommended in practical applications when the return value of the multicast delegate is generally void and the delegate type is non-void type.

Nature of the Commission

The delegate is still essentially a class

The class inherits from the System.MulticastDelegate class, which maintains a list of delegates with links, which are invoked in the order of the delegate list when the multicast delegate is called. Also includes a constructor that accepts two parameters, and three important methods Begininvoke,endinvoke and invoke

Visible in the IL code, a constructor is first used to create a mydelegate instance, and then the callback method call is executed through Calcdelegate::invoke, and the Invoke method is the one that actually executes the call. Therefore, you can also display the call in code by using Invoke.

Mydelegate.invoke (12);
Anonymous methods

Anonymous methods are placed inline with the location of the delegate object, avoiding the creation of a delegate to associate the callback method, which is called by the delegate by the anonymous method

The following example implements the above example in an anonymous way

            Delegate (intint  y)            {                + y);            };             Delegate (intint  y)            {                - y);            };            Myadddelegate (12);            Mysubstractdelegate (21);

In fact, anonymous methods and delegates are equivalent on IL, and the compiler is an anonymous method with two static members and static methods

Lambda expression

c#3.0 introduces a lambda expression that simplifies the syntax of anonymous methods. It is easy to convert an anonymous method to a lambda expression by following these steps.

    • Delete delegate keyword
    • Put the lambda operator between the argument list and the anonymous method BODY = =

The following example demonstrates a lambda expression

Calcdelegate myadddelegate = (intint y) + =            {                + y);            }            ; = (intint y) = =            {                - y);            };

The compiler allows us to further simplify the lambda expression by inference

    • The compiler can know the parameters of the delegate type from the declaration of the delegate, so lambda allows us to omit the type parameter
    • If there is only one implicit type argument, you can omit the parentheses
    • If the statement block contains a return statement, you can replace the statement block with the expression after the return keyword

The key points for the Lambda parameter list are as follows

    • The parameters of the lambda expression argument list must match the delegate in the number of arguments, type, and position
    • Parameters in the argument list of an expression do not necessarily need to contain a type unless the delegate has a ref or out parameter
    • If there is only one argument and is an implicit argument, parentheses can be omitted
    • If there are no arguments, you must use empty parentheses ()

[C # Foundation] Delegate

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.