"Restudying" C # Delegate Delegate

Source: Internet
Author: User

In the C # learning process, learn to entrust and events always confused for a period of time, after the confusion since then indefinitely ~, so recently I intend to learn the past confused knowledge summary, restudying, summary record down.

First, let's take a look at MSDN's definition of a delegate:

The delegate keyword is used to declare a reference type that can be used to encapsulate a named method. A delegate is roughly similar to a function pointer in C + +, but a delegate is type-safe and reliable.

delegate allows you to pass a function as a parameter. The type safety of the delegate requires that the function passed as delegate has the same signature as the delegate declaration.

A delegate is the basis of an event.

As we all know, functions in C + + can be used as arguments by function pointers, and there is no pointer in C #. So make a delegate out.

However, compared to function pointers, delegate has many advantages that function pointers do not have. First, the function pointer can only point to a static function, and delegate can reference both static and non-static member functions.

When referencing a non-static member function, delegate not only holds a reference to this function's entry pointer, but also holds a reference to the class instance that called the function. Second, delegate is an object-oriented, type-safe, reliable controlled (managed) object compared to a function pointer.

In other words, runtime ensures that delegate points to an effective method, and you don't have to worry about delegate pointing to an invalid address or an out-of-bounds address.

Next, let's look at how C # code declares, instantiates, and uses a delegate:

Private Delegate void MyDelegate (string  msg); Static void Notify (string  name) {Console.WriteLine ("Notification received for: {0}"  , name);} MyDelegate mydelegate=new  mydelegate (Notify); MyDelegate ("yoyoyo! ");

One of the things to note is:

1. The delegate cannot be defined as static.

2, return type, function parameters must be the same as the delegate function (when inheriting).

3. Delegates can be linked together; For example, multiple methods can be called on an event. Operation via +=,-=.

See here, we generally know that "entrust" is something, but, believe that the beginner has a lot of questions, commissioned specifically what is to do??? How to use it when writing a program? These problems have been bothering me for a long time.

"Entrust" in the literal sense: entrust the matter to others or other institutions, and give examples of daily life:

Lunch time, because the work is not finished, so ask colleagues to bring a lunch, this is a "delegation."

Play the game upgrade too slow, which has so much time to upgrade, decisive for someone to help leveling ~ Fast and comfortable ~ full level after the number to me, which is also a "delegation."

In short, it is when you are busy to ask someone else to help you do things, which reminds us of what? ----- Asynchronous Programming ! , for example, in the case of time-consuming operations, asynchronously without affecting the main thread, especially the UI thread, the delegate delegate, in most cases, is used to act as a "runner" in asynchronous programming.

Here we do not discuss asynchronous programming, nor involve asynchronous programming, otherwise it is far away, let us through an example to understand the basic role of delegate it.

There is such a scene:

Puppy Love is a concern of many parents, ah, recently parents a seems to find their children Lilei parents B's children Hanmeimei interesting, and parents B also found that, in order to confirm the situation, the parents privately commissioned the teacher to find out the real situation when the notice, early correction of students ' ideas ~.

Simple Code Simulation Scenario:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespacedelegate{classProgram {Static voidMain (string[] args) {            //parents A, B, they can't go to school to watch the kids one day? Entrusted to the teacher, I still have to go to workParent PA =NewParent (); Parent PB=NewParent (); //parents A, a, respectively, commissioned the teacher to find puppy love situation notify themTeacher Teacher =NewTeacher (); Teacher. Notifystudentlove=Pa.            receivemsg; Teacher. Notifystudentlove+=PB.            receivemsg; //The teacher began to check the puppy love situationteacher.        Checklove (); }    }}

Teacher Class:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegate{ Public classTeacher {//declares a delegate type that notifies parents         Public Delegate voidNotifydelegate (stringmsg); //the teacher was instructed to 1 delegates//define a delegate: Notify parents when they find puppy love ( and events only one event keyword!) )         Publicnotifydelegate Notifystudentlove;  Public voidChecklove () {//one day ab classmate suddenly dispute! was found by the teacher!             stringmsg ="a classmate and b classmate Puppy love!! "; //Check whether a parent commissioned the teacher to inform puppy love            if(Notifystudentlove! =NULL)            {                //To inform parents decisivelyNotifystudentlove (msg); }        }    }}

Parent class:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegate{ Public classParent {/// <summary>        ///Receiving Messages/// </summary>        /// <param name= "MSG" >notification message</param>         Public voidReceivemsg (stringmsg) {Console.WriteLine ("parents receive notification:"+msg); }    }}

Operation Result:

Parents receive notice: A classmate and b classmate Puppy love!!
Parents receive notice: A classmate and b classmate Puppy love!!

After reading the above code scenario, I believe that delegate has a more in-depth understanding, that is, "to help me Do", but also vaguely feel the Observer mode ?

Yes, if you can only use delegate to achieve the observer pattern, but, in terms of object-oriented, the external object is given delegate too many methods, but also the instantiation of new, is +=,-=, even you can =null.

for the Observer pattern, the observer cannot and should not have permission to instantiate the message list of the event Publisher, and the observer should not be able to control the event Publisher's notification of events, all of which should be internal to the publisher and not be controlled by external objects .

Above the simulation scene, you can call teacher in the scene. Notifystudentlove (); But in principle it should be only in teacher. Called only within the Checklove () function.

Some students think, then we encapsulate one more time Notifystudentlove commissioned it? For example:

Private notifydelegate Notifystudentlove;  Public void  + = newdelegate;}

Yes, we can do this-and that's what the keyword event does for us.

After the event keyword has been added,. NET wraps the delegate in a series of ways, encapsulating a portion of the behavior that should not otherwise be exposed, like the syntax sugar {get;set;} The same.

At this time, the "delegation" turned into an "event" ~! But don't think you're wearing a vest and I don't know you.

The next section will tell you about the "restudying" C # event, which is welcome to shoot bricks.

"Restudying" C # Delegate 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.