C # Delegate

Source: Internet
Author: User

1. What is a delegate

In terms of data structures, delegates are the same type of user-defined types as classes.

A delegate is an abstraction of a method that stores the address of a series of methods that have the same signature and return type. When the delegate is invoked, all the methods contained by the delegate are executed.

2, the definition of the delegation

A delegate is a type, as if the class were a type. As with classes, a delegate type must be declared before it is used to create variables and type objects.

The Declaration prototype of a delegate is
Delegate < function return type > < delegate name > (< function parameter >)

Example: public delegate void MyDelegate (int number);//defines a delegate mydelegate, which can register a function that returns a void type and has an int as a parameter

3, the instantiation of the delegate

3.1 Using the New keyword

The prototype of the delegate instantiation is
< delegate type > < instance alias >=new < delegate type > (< registration function >)
Example: MyDelegate _mydelegate=new mydelegate (CHECKMOD);//using a function Checkmod to instantiate the above MyDelegate delegate as _mydelegate

3.2 Using anonymous Methods

< delegate type > < instance alias >=delegate (< function parameter >) {function Body};

3.3 Using lambda expressions

1  class Program2     {3         //declaring a delegate4         Delegate intMyDelegate (intXinty);5 6         Static voidMain (string[] args)7         {8             //instantiating a delegate9             //1. Use the New keywordTenMyDelegate _mydelegate =Newmydelegate (getsum); One  A             //2. Using anonymous Methods -MyDelegate mydelegate =Delegate(intXinty) -             { the                 returnX +y; -             }; -  -             //3. Using lambda expressions +MyDelegate Mydelegatelambda = (intXintY) = = {returnX +y;}; -         } +  A         Static intGetsum (intXinty) at         { -             returnX +y; -         } -}

4. Generic delegate

Delegates also support the use of generics
Generic delegate Prototypes:
Delegate <T1> < delegate name ><T1,T2,T3...> (T1 t1,t2 t2,t3 t3 ...)

For example: Delegate T2 delegatedemo<t1,t2> (T1 t);//defines a delegate with two generics (T1,T2), T2 as a delegate function return type, T1 as a delegate function parameter type

Static Boo Check (int i)
{
if (i%2==0)

{

return true;

}

return false;
}

static void Main (string[] args)
{
Delegatedemo<int, bool> _delegate =check;//The generic delegate delegate <T1,T2> instantiate as <int,bool> That is, a function that has an int type parameter and the return type is bool.
Console.WriteLine (_delegate (9));//false
}

5. C # built-in generic delegate

There are 3 built-in generic delegates in C #

1 namespaceDelegatedemo2 {3     class Program4     {5         //declaring a delegate6         Delegate intMyDelegate (intXinty);7 8         Static voidMain (string[] args)9         {Ten             //1. action<t> only delegate must be a method with no return value Oneaction<string> _action =Newaction<string>(SayHello); A_action ("Hello World"); -  -             //2, Fun<tresult> only the method that the delegate must have a return value thefunc<int,BOOL> _func =Newfunc<int,BOOL>(Check); -_func (5); -  -             //3, predicate: This delegate returns a bool value, which typically refers to a "judging condition function".  +             //It should be noted that the criteria are generally "external hard conditions", such as "greater than 50", rather than being specified by the data itself, such as "finding the largest element in an array is not appropriate."  -predicate<int> _predicate =Newpredicate<int>(Check); +             //using lambda expressions Apredicate<int> predicate = p = p%2==0; at_predicate ( -); -         } -  -         Static voidSayHello (stringSTRMSG) -         { - Console.WriteLine (STRMSG); in         } -  to         //The return value is a bool value +         Static BOOLCheck (inti) -         { the             ifI2==0) *             { $                 return true;Panax Notoginseng             } -             return false; the         }        +     } A}

6. Multicast delegation

When instantiating a delegate, a matching function must be registered to the delegate to instantiate a delegate object, but an instantiated delegate can not only register a function but also register multiple functions, and after registering multiple functions, each registration function is executed sequentially according to the registration sequence of the registered function when the delegate is executed.

Prototype of the function registration delegate:
< delegate type > < instance alias >+=new < delegate type > (< registration function >)
For example: MyDelegate _mydelegate+=new mydelegate (CHECKMOD);//Register the function checkmod on the delegate instance _checkdelegate
At the beginning of. NET 2.0, you can register a matching function directly with the instantiation delegate:
< delegate types > < instance aliases >+=< registration functions >
For example: MyDelegate _mydelegate+=checkmod;//registers the function checkmod on the delegate instance _mydelegate

Note: Delegates must be instantiated before using + = To register other methods. if the delegate instance that is registered with the function is assigned from the new = sign, it is equivalent to re-instantiating the delegate, and there is no relationship between the previously registered function and the delegate instance .

There is a + = Registration function to the delegate, there is the-= de-Registration

For example: MyDelegate _mydelegate-=checkmod;

If the delegate has a return value after the delegate has registered more than one function, the return value of the last registered function is returned when the delegate is invoked.

1 namespaceDelegatedemo2 {3     class Program4     {5         //declaring a delegate6         Delegate intMyDelegate (intXinty);7 8         Static voidMain (string[] args)9         {TenMyDelegate _mydelegate =Newmydelegate (FUN1); One_mydelegate + =fun2; AConsole.WriteLine (_mydelegate (Ten, at)); -  -Console.readkey ();//output 10, returns the return value of the last registered function the         } -  -         Static intFUN1 (intXinty) -         { +             returnX +y; -         } +  A         Static intFun2 (intXinty) at         { -             returnx; -         }       -     } -}

C # Delegate

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.