Delegates in C #

Source: Internet
Author: User

Doing the project for a while, often using delegates and some lambda expressions, here is also a summary of these things.


1. What is a delegate?

To tell the truth, with so many, suddenly let's talk about the definition of the Commission, indeed there are difficulties. In my opinion, the delegate is similar to the usual method, but the function is very powerful. Strong to Where? The method can have parameters, since the delegate is similar to a method, so there are parameters, but the contents of the arguments can be methods.

2. Delegate usage

A delegate is particularly similar in usage to the use of a class, such as when a class is used, and must be instantiated first. Let's look at a demo

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >namespace consoleapplication1{public    class B    {        //define a Delegate object        //Because a method is passed in the delegate, this delegate is like a model        of some method For example, a delegate defined at this time requires that the passed-in method return value is void        //The parameter must be a string of type        delegate void Test (string name);        Test method one public        static void Test1 (string name)        {            Console.WriteLine (name);        }        Test method Two public        static void Test2 (String age)        {            Console.WriteLine (age);        }        Use        a delegate static void Main (string[] args)        {            //Use            a delegate//usage similar to a class, you must first instantiate a delegate object before using            test test = new test (Test1);            By instantiation, the delegate becomes a proxy            test ("principal") of the method;                         Console.ReadLine ();}}}    </span>


Summary: Through the above code, we also see that in the usage of the delegate is similar to the class, functionally similar to the method.



3. Anonymous delegation

Look at the above code, basically is to have a preliminary understanding of the delegation, as long as the following usage can be mastered. Let's take a look at the anonymous delegate, just like a delegate, but a little bit of a change of shape.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" > Public  class C     {        static void Main (string[] args)        {//             pre-use also needs to be instantiated, now anonymous delegate            // No more instantiation of the delegate object            //An anonymous delegate written using lambda expression            delcompare del = (T1, t2) + {return t1+t2;};            Direct Anonymous delegate            delcompare Del1 = delegate (int t1,int T2) {return t1+t2;};            Call delegate method            int n = del (3, 4);            int n1 = Del1 (3, 4);                    }    } </span>


The above code is only on the basis of the delegation, changed the type. In the end, through the above two code show, we already know that the method of using the delegate has three kinds of forms.


4. Asynchronous delegation

Small in the study commissioned, looked at the MSDN documentation, found a good thing. An asynchronous delegate.

BeginInvoke method : Executes the specified delegate asynchronously on the thread that creates the control's underlying handle.

The specific implementation principle, is not very clear, but see the asynchronous execution of the specified delegate, small series is a little excited. So the small part of the method to execute the Commission, compared with the above, found to be 1000 times times faster. Don't say anything, just go to the code!


<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >   delegate void Deltest ();    public class D    {        ///callback function, method public        static   void Callback (IAsyncResult ar)        {            When the method of the asynchronous delegate is finished executing Console.WriteLine ("Over");              }        static void Main (string[] args)        {            //instantiation of Delegate object            deltest del = Test;            The delegate's asynchronous call to            Del. BeginInvoke (Callback, null);            Console.WriteLine ("Test");        }        public static void Test ()        {            Console.WriteLine ("Test");        }    } </span>

5.action<T> Delegates and func<T,TResult> Delegates

Considerate of Microsoft, really is serving the world ha. Looking at the tedious process of delegating the above, Microsoft has encapsulated two functions for us based on this consideration.


func<T,TResult>: encapsulates a method that has a parameter and returns the type value specified by the TResult parameter.

Action<t>: Encapsulates a method that has only one parameter and does not return a value.

The difference between the two is that there is no return value, specific examples, you can refer to MSDN, here is a little mention.






Delegates in C #

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.