------Delegate for C # basics

Source: Internet
Author: User

First, the basic introduction of the delegation

A task delegate can be an object that holds one or more methods. Of course, you're not going to execute an object under normal circumstances, but the delegate is different from the object. A delegate can be executed, and this is the method by which the delegate executes his "hold".

A chestnut just like your daughter-in-law let you buy two buns, you are the Commission, buy steamed buns is you hold the method, of course, this raised the chestnut slightly inappropriate, but can help understand some of the basic concept of delegation.

Overview of Delegates:
comparison of Delegates to Objects
Claim type declaring classes Declaring a delegate (type)
Declaring a variable of type Declaring a variable of a class type Declaring a variable of a delegate type
fill variable

Span style= "Font-family:microsoft Yahei; font-size:16px; Background-color: #c0c0c0; " > Create a tired instance and put

Its reference is assigned to the variable

Create an instance of the delegate and put

Its instance is assigned to a variable and

Add a method

Using variables Working with Class objects Invoke delegate

Second, the basic use of the Commission

1. Declaration of Delegation:

Delegates, like classes, must be declared before creating variables and types.  

Delegate  void  Demo (int x)

Delegate: Delegate's keyword

void: return type

Demo: Delegate type name

(int x): Signature

2. Create the Delegate object:

To create a delegate variable

Demo Mydemo;

To create a delegate object

mydemo=New  Demo (instance name. method) Mydemo=New demo (class name. method)

Create a delegate object to have a delegate name, inside the parentheses is the method that is added to the delegate, either an instance method or a static method.

We can also use the shortcut syntax class to create a delegate, which only consists of the method specifier.

mydemo= instance name. Method Mydemo= Class name. method

This can be done because there is an implicit conversion between the method name and its corresponding delegate type.

3. Assigning a value to a delegate:

Because the delegate is a reference type , we can assign a value to the delegate to change the reference contained within the delegate variable, and the original delegate object will be reclaimed by the garbage collector after the change.

Mydemo=insertobj.other1

4. Combination of Delegates:

Delegates can be "combined" by using additional operators. This operation creates a new delegate whose invocation list is connected to a copy of the invocation list of the two delegates as operands.

Mydemo demo1=mathod.mym1; Mydemo Demo2=sclass.mym2; Mydemo Demo3=demo1+demo2;

The combined delegate always feels as if the operand has been changed. In fact, the delegate is constant , and the delegate object cannot be changed after it is created.

(The method in the illustration is different from the code, meaning the same.) )

5. Add a method to the delegate:

Operator: + =

Mydemo demo=Inst. Mym1;demo+ =Scl.m3;demo+=x.act;

When adding a method to a delegate, the delegate is actually immutable , and when the method is added to the delegate, it is actually a new delegate.

So the result of adding three methods to the delegate is actually a variable pointing to a completely new delegate .

6. Removal Method:

Operator:-=

The removal method, like the Add method, essentially creates a new delegate, the new delegate is a copy of the old delegate----The value is not a reference to the method that has been removed.

7. Invoke the delegate:
Mydemo demo=Inst. Mym1;demo+ =Scl.m3;demo+=x.act;
Demo (123);//Invoke Delegate

If a method appears more than once in a delegate, it is executed once every time the method is encountered in the execution list.

8. Complete delegate instance:
Delegate voidMydele (stringstr);  Public classMyclass { Public voidPRITSTR1 (stringstr)        {Console.WriteLine (str); }         Public Static voidPRITSTR2 (stringstr)        {Console.WriteLine (str); }    }    classProgram {Static voidMain (string[] args) {Myclass CLA=NewMyclass (); Mydele Dele= Cla. PRITSTR1;//instantiating a delegate//Adding a method to a delegateDele + =myclass.pritstr2; //Invoke DelegateDele"Test it.");        Console.readkey (); }    }

9. Delegates with return values:
 Delegate intMydele ();  Public classMyclass {intstr =Ten;  Public intPritStr1 () {returnstr+=1; }         Public  intPritStr2 () {returnstr+=2; }    }    classProgram {Static voidMain (string[] args) {Myclass CLA=NewMyclass (); Mydele Dele= Cla. PRITSTR1;//instantiating a delegate//Adding a method to a delegateDele + =CLA.            PRITSTR2; //Invoke DelegateConsole.WriteLine ("The return value is: {0}", Dele ());        Console.readkey (); }    }

10. Call a delegate that uses a reference parameter:

The reference parameter in the delegate is the same as in the method. The value address passed by the parameter, so the operation of the numeric value is reflected in each method.

 Delegate voidMydele (ref intx);  Public classMyclass { Public voidPRITSTR1 (ref intx) {x+=2; }         Public voidPRITSTR2 (ref intx) {x+=1; }    }    classProgram {Static voidMain (string[] args) {Myclass CLA=NewMyclass (); Mydele Dele= Cla. PRITSTR1;//instantiating a delegate//Adding a method to a delegateDele + =CLA.            PRITSTR2; //Invoke Delegate            intx =5; Dele (refx); Console.WriteLine ("the value of x is {0}", x);        Console.readkey (); }    }

Iii. Some extensions of the delegation

Anonymous method:

Anonymous methods are generated because there are methods in the program that only need to be executed once, in the spirit of the most time-saving, labor-saving approach, the program ape Daniel invented--anonymous method . A method that does not require the declaration, creation of an instance, or direct use with a delegate.

--Common named method (lowto burst )

  Delegate intMydele (intx);  Public classMyclass { Public intPRITSTR1 (intx) {x+=2; returnx; }    }    classProgram {Static voidMain (string[] args) {Myclass CLA=NewMyclass (); Mydele Dele= Cla. PRITSTR1;//instantiating a delegateConsole.WriteLine ("the value of x is {0}", Dele (Ten)); Console.WriteLine ("the value of x is {0}", Dele (1));        Console.readkey (); }    }

--Anonymous method ( Gaofu )

 classProgram {Delegate intMydele2 (intx); Static voidMain (string[] args) {Mydele2 dele=Delegate(intx) {returnX +Ten;            }; Console.WriteLine ("the value of x is {0}", Dele (1));        Console.readkey (); }    }
Syntax for anonymous methods:

The primary syntax for anonymous methods includes:

1.delegate, keywords.

2. The parameter list can be omitted if the statement block does not have any parameters.

3. Statement block, which contains code for anonymous methods.

1. Return type

The anonymous method does not display a declared return value , and when implementing an anonymous method, you must return a value of the same type as the delegate return type. If the delegate declares void, the anonymous method cannot have a return value.

This is in accordance with the basic concept of the delegate, both the parameter and the return type need to be consistent with the declaration of the delegate .

2. Parameters

The method signature must match the delegate.

The signature includes: 1. Number of parameters 2. Parameter type and position 3. modifier

The argument list is omitted if : 1. The delegate parameter does not contain any out modifiers. 2. The anonymous method does not apply to any parameters.

3.Params parameters

The last parameter must be a Params when declaring a delegate type

The list of anonymous parameters is the one that can ignore the params keyword

Delegate void Mydele (int x,paramsint[]  y); Mydele dele=delegate(int x,int[] y) {// specific code };
4. Scope of anonymous method variables
    • Variables in the perimeter scope are called external variables.
    • The external variables in the code implemented in the anonymous method become method captures.
Delegate voidMydele (intXparams int[] y);intxx=5; Mydele Dele=Delegate(intXint[] y) {//Specific CodeConsole.WriteLine ("capture: {0}", XX);//external variables are used};console.writeline ("{0}", x);//compilation error, out of scope

Lambda expression:

Lambda expressions are actually the 2.0 of delegates and anonymous methods that are simpler and more convenient.

Delegate (int x)      {return x+1;};/ /anonymous method Mydele dele=         (int x) =   {return x+1;};/ /Omit delegate Use = = (goes to) mydele dele=             (x) + =   {return x+1;};/ /omit type Mydele dele=               x =   {return x+1;};/ /omit parenthesis Mydele dele=               x =    x+1;         

----->>>> a long way to go, how can this hard road without your support and encouragement.

------Delegate for C # basics

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.