What is the delegate in C? Is an event a delegate?

Source: Internet
Author: User

For more information about this section, see. NET and C # advanced programming (version 4).

 

1. Understand Delegation

We know that a callback function is actually a pointer to a method call, that is, a function pointer. In. net, the function pointer concept is implemented in delegate mode .. The main reason for using delegation in. NET is that it is of type security. Why? In the past, for example, in C, the function pointer was just a pointer to a storage unit, so we could not tell what the pointer actually points, the delegate determines the return value type and parameter list pointing to the method. Note that a delegate is not equivalent to a method, but a reference type.

 

1. Definition of delegation

Definition of delegation
// Step 2: declare a delegate
Public Delegate void calculatedelegate (int x, int y );

// Step 2: Create a method associated with the delegate, which has the same return value type and parameter list
Public void add (int I, Int J)
{
MessageBox. Show (I + J). tostring ());
}

// Step 2: Define the delegate Type Variable
Private calculatedelegate mydelegate;

Public void getdelegateex ()
{
// Step 4: bind the delegate
Mydelegate = new calculatedelegate (ADD );

// Step 2: callback add Method
Mydelegate (1, 2 );
}

 

Iii. multicast Delegation

Pay attention to the following two points in multicast delegation:

(1) + = and-= operations. In fact, they call the delegate. Combine and delegate. Remove methods respectively.

(2) the return value of the multicast delegate is generally void. If the delegate type is not void, the multicast delegate returns the execution result of the last called method, in practice, this application is not recommended.

 

Iv. Nature of delegation

As mentioned above, a delegate is a reference type, which is essentially a class, compiling the above Code as Il:

 

 

We can see that:

(1) delegate calculatedelegate to a class that inherits from system. multicastdelegate

(2) calculatedelegate constructor: when creating a delegate-type instance, a reference to the object will be initialized for it (this point points to the delegateex object) and an integer that identifies the callback method, completed by the compiler.

(3) The invoke method is actually called.

 

V. Delegation and events 

We can see from the previous sample code that we can operate on the delegate at Will on the client, which breaks down the object-oriented encapsulation mechanism to a certain extent .. Net event model is built on the delegate mechanism, which encapsulates the delegate.

Event transmitter: it can be an object or assembly in an application, and its main function is to trigger an event.

Event receiver: Any application, object, or component that is notified when something occurs.

How can a sender notify a receiver? We define a method somewhere in the event receiver, which is responsible for event processing and executes this event processing program every time a registered event occurs. Since the sender has no knowledge of the receiver, it is necessary to use the delegate as the intermediary. The sender defines the delegate to be used by the receiver to register the event handler into the event.

First, let's take a look at this code: btnsave. Click + = new eventhandler (btnsave_click ). We often see this in programming. It tells us that the btnsave_click method should be executed when the Click Event of the btnsave button is triggered. Eventhandler is the delegate that an event is used to assign a handler (btnsave_click) to an event (click.

Code
// Define an internal event parameter type to store the status information transmitted to the handler when an event is triggered.
Public class calculateeventargs: eventargs
{
Public readonly int X, Y;

Public calculateeventargs (int x, int y)
{
This. x = X;
This. Y = y;
}
}

// Declare the event Delegate.
Public Delegate void calculateeventhandler (Object sender, calculateeventargs E );

Public class Calculator
{
// Defines event members and provides external binding.
Public event calculateeventhandler mycalculate;

// Define the method responsible for notifying the event, that is, the entrusted invoke method call.
Protected virtual void oncalculate (calculateeventargs E)
{
If (mycalculate! = NULL)
{
Mycalculate (this, e );
}
}

// Call this method to display a new event method.
Public void calculate (int x, int y)
{
Calculateeventargs E = new calculateeventargs (x, y );

// Notify the registrant of all events
Oncalculate (E );
}
}

 

A Complete Event program is defined above. Now, you only need to define an event trigger program.
Public class calculatermanager
{
Public void add (Object sender, calculateeventargs E)
{
MessageBox. Show (E. x + E. Y). tostring ());
}
}

Static void main ()
{
Calculator calculator = new calculator ();

Calculatermanager manager = new calculatermanager ();

Calculator. mycalculate + = manager. Add;
Calculator. Calculate (1, 2 );
}

Related Article

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.