On the delegate in C #

Source: Internet
Author: User

Introduction

Delegate is an existing feature of Dotnet1.0, but it has not been collated since it has never had a chance to use the delegate feature in real work. These two days, I re-read some information about delegate and began to formally organize the famous features in C #. This paper will discuss the characteristics of delegate.

What is a. Delegate?

Delegate Chinese translation as "delegation". The explanations for delegate in MSDN are as follows:

a delegate in C # is similar to a function pointer in C or C + +. Using delegates enables programmers to encapsulate a method reference within a delegate object. You can then pass the delegate object to the code that invokes the referenced method without knowing at compile time which method will be called. Unlike function pointers in C or C + +, delegates are object-oriented, type-safe, and secure.

If you are the first to contact delegate this concept, you may be the above text feel unintelligible, but it does not matter, you can first think of delegate is a function pointer.

And when you are faced with a concept of nothingness, the best way to deal with it is to look at the examples directly. The following is a simple example of delegate use.

Class Program {Staticvoid Otherclassmethod () {Console.WriteLine ("Delegate an Other class ' s method"); }Staticvoid Main (String[] args) {var test =New Testdelegate (); Test.delegatemethod =New Testdelegate.delegatemethod (test. Nonstaticmethod); Test.delegatemethod + =New Testdelegate.delegatemethod (Testdelegate.staticmethod); Test.delegatemethod + = Program.otherclassmethod; Test. Rundelegatemethods (); } }class testdelegate {public delegate  void Delegatemethod (); //declares a delegate Type public Delegatemethod Delegatemethod; //declares a delegate object public static void Staticmethod () {Console.WriteLine ( "Delegate a static Method");} public void Nonstaticmethod () {Console.WriteLine ( " Delegate a non-static method "); } public void rundelegatemethods () {if (delegateMethod! =) Span class= "KWRD" >null) {Console.WriteLine (   
                   Console.WriteLine ("---------");     }}

Above is a delegate use example, run to see the results. Let me explain a little bit:

"1" public delegate void Delegatemethod (); this declares a delegate type, called Delegatemethod, which can be carried: a function with a return value of void and no parameters passed in.

"2" publicDelegatemethod Delegatemethod; This declares a Delegatemethod object (that is, an object that declares a type of delegate).

Differentiate: Delegatemethod is a type, Delegatemethod is an object.

"3" Why does it say that delegate can be seen as a function pointer? Look at the following code:

Here Delegatemethod is equipped with 3 functions, and can be operated by calling Delegatemethod.invoke (); This is why delegate can be thought of as a function pointer. In the above code, Delegatemethod can only be carried: a function with a return value of void, with no parameters passed in (see: Nonstaticmethod,staticmethod,otherclassmethod definition), This is related to the delegate type declaration (see Delegatemethod declaration: Public delegate void Delegatemethod ()).

"4" delegate when carrying multiple methods, the function can be increased by + =, or a function in delegate can be removed via-=.

Two. Differences in function pointers in delegate and C + +

Delegate and C + + function pointers are very similar, but if deep contrast, found that there is still a difference, the difference is mainly three aspects (refer to the Stanley B. Lippman an article)

1) A delegate object can carry multiple methods (methods) at a time, rather than one at a time. When we evoke a delegate with multiple methods (methods), all methods are recalled in order of their "being carried to delegate objects".

2) The method (methods) that a delegate object is carrying does not need to belong to the same category. All the methods (methods) that a delegate object carries must have the same prototype and form. However, these methods (methods) can be static and non-static, and can consist of one or more different categories of members.

3) A declaration of delegate type essentially creates a new subtype instance, which is derived from the abstract base classes Delegat of the. NET Library Framework E or multicastdelegate, which provide a set of public methods to inquire about the delegate object or its carrying method (methods) , unlike function pointers, delegates are object-oriented, type-safe, and secure.

Read the above about delegate, I believe you have some understanding of it, the following we will be more in-depth discussion!

Three. When should delegate be used?

After reading the above introduction, you can have some questions, why there are delegate? When does it actually work? When should I use it? Before answering these questions, let's take a look at the following code:

    Class Program {Staticvoid Main (String[] args) {var car =New Car (15);New Alerter (CAR); Car. Run (120); } }Class Car {PublicDelegatevoid Notify (IntValue);PublicEvent Notify Notifier;Privateint petrol = 0;Publicint Petrol {get {return petrol; } set {petrol =Valueif (Petrol < 10)//When the value of petrol is less than 10 o'clock, departure alert {if (notifier! =NULL) {notifier. Invoke (Petrol); } } } }public Car (int petrol) {petrol = petrol;} public void Run (int speed) {int Distance = 0; while (Petrol > 0) {thread.sleep (500); petrol--; Distance + = speed; Console.WriteLine ( "Car is running ... Distance is "+ Distance. ToString ()); }}} class Alerter {public Alerter (car car) {car.notifier + = n EW car.notify (Notenoughpetrol); } public void Notenoughpetrol (int  Value) {console.foregroundcolor = consolecolor.red; Console.WriteLine ( "You are only having" + value. ToString () +  "gallon petrol left!"); Console.resetcolor (); } } 

After reading the above code, you might ask: Why not call Alerter.notenoughpetrol directly in public int petrol? Because the car module and the Alerter module itself are two separate subsystems, if called directly, the coupling will increase, which is not what we would like to see.

In fact, the above code is the implementation of the Observer pattern in the design pattern (Observer mode, also known as the Source/listener mode), when the car is running in the <10 of gasoline, the alarm will be issued alarm. In the above code, delegate is equivalent to a function pointer that holds the callback function, and with delegate, we can implement the observer pattern very conveniently. In fact, we can consider using delegate when we need to use a callback function.

I wonder if you have noticed that there is a problem in the code above?

Event Notify Notifier;

In the above code, we define an event, and in fact:

Public Notify notifier;

This writing, also fully satisfies our needs, which leads us to another problem, delegate and event!

Four. Delegate and event

"1" The relationship between delegate and event

Look at the Microsoft code, we will find delegate and event these two keywords will often appear together! What exactly is their relationship?

In MSDN, a paragraph describing the relationship between delegate and event is simple:

Declaring an event: to declare an event within a class, you must first declare the delegate type of the event.

Effects of "2" delegate and event use

Look at the following pictures, which I cut off from a C # application program:

From the view, in response to the graphical interface of the operation, we use the event and delegate, we believe this also we use the event and delegate the most frequent place. Here I also want to wordy, usually need our own code to write the interface event response function, such as: Button_Click (...), is actually a callback function, in the auto-generated file Form1.Designer.cs, vs the event and its corresponding callback function (that is: Button_ Click (...) And so on), the corresponding callback function executes when an event is triggered.

Difference between "3" "PublicNotify notifier" and "Public event Notify notifier"

On this issue, let's take a look at the IL code directly ildasm:>

Il code for "public Notify notifier",

Il code for "public event Notify notifier",

The difference is already very obvious, "publicNotify notifier" equivalent to the field in class, access level is public, and "public event Notify Notifier" is equivalent to the property, the access level is private! As a result of the above differences, they will be slightly different in some use, detailed can refer to the SHENSR written "Delegate vs.".

Five. Invoke and BeginInvoke methods in delegate

To put it simply, invoke and BeginInvoke are all carry functions in the delegate, and the difference is that invoke is a synchronous method, and BeginInvoke is an asynchronous method. About this, there is an article "Invoke and BeginInvoke", the introduction of the more detailed, here is not much to say.

Six. Summary

To recap, when and where we might use the delegate:

On the delegate 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.