Use delegation in C # events and Multicast

Source: Internet
Author: User

(1) What is delegation?

1. Delegate can be seen as a new type of object in C # (delegate is a type that saves method reference in the object ). The delegate passes a method as a parameter to another method through the address transfer mechanism. It is equivalent to a C/C ++ function pointer, but it is a type-safe function pointer. The delegate can have multiple methods.

2. Delegation is an instance of a class derived from the base class system. Delegate.

3. Generally, parameters in a function are transmitted with data. However, if we need to pass a method in a function parameter, we need to use a delegate. The operations performed by a method are not performed on data, but on another method. During compilation, we do not know what the second method is. This information can only be obtained at runtime. [1] delegate is required to pass methods to other methods.

4. The question of delegate processing can be handled using function pointers in C ++, but can be handled using interfaces in Java. It improves the function pointer mode by providing type security and supporting multiple methods; it improves the interface method by calling methods without the need for internal class adapters or additional code to handle multi-method calls. [2]

(2) How to Use delegation?

1. Define Delegation

The delegate keyword is added before the definition. Because the definition delegate basically defines a new class, the delegate can be defined anywhere in the definition class, or externally in any class. You can also define the delegate as a top-level object in the namespace. According to the defined visibility, you can add general access modifiers on the delegate. [1]
Format:
<Access modifier> DeleGate <returntype> handlername ([parameters])
Example:
Delegate double doubleop (Double X );

2. Use Delegation

In C #, the delegate syntax always carries a parameter function. This parameter is the delegate application method. The method used by the delegate must be consistent with the delegate Declaration, that is, the parameter list and return value are consistent.

A delegated instance can represent an instance method of any type of object or a static method of any type.
The following two examples are described respectively:
(1) Delegated instances can represent the instance methods of any object of any type.
// Create an object
Mathoperations instanceexmaple = new mathoperations ();

// Delegate the method of the object as a parameter
Doubleop instanceexmaplemethod = new doubleop (instanceexmaple. multiplybytwo );

(2) Delegated instances can represent any type of static methods.
// Pass the static method of the class as a parameter to the Delegate
Doubleop staticexmaplemethod = new doubleop (mathoperations. dividebythree );

3. Complete example:

Using system;

Namespace delegate
{
 
Class mathoperations
{
// Multiply by 2
Public double multiplybytwo (double firstarg)
{
Return firstarg * 2;
}

// Divide by 3
Public static double dividebythree (double firstarg)
{
Return firstarg/3;
}
}

Class mathexample
{
Delegate double doubleop (Double X );
 
Static void main (string [] ARGs)
{
Mathoperations instanceexmaple = new mathoperations (); // create an object
Doubleop instanceexmaplemethod = new doubleop (instanceexmaple. multiplybytwo); // delegate the method of the object as a parameter

Doubleop staticexmaplemethod = new doubleop (mathoperations. dividebythree); // transmits the static method of the class as a parameter to the Delegate

Double fstresult, scdresult;

// The results of the following two methods are the same. instanceexmaple. multiplybytwo (5.0) is equivalent to instanceexmaplemethod (5.0)
Fstresult = instanceexmaple. multiplybytwo (5.0); // use the object Method
Scdresult = instanceexmaplemethod (5.0); // use the delegate

// Print the above result
Console. Write ("instanceexmaple. multiplybytwo Result:" + fstresult. tostring ());
Console. writeline ();
Console. Write ("instanceexmaplemethod Result:" + scdresult. tostring ());
Console. writeline ();

// The results of the following two methods are the same, and mathoperations. dividebythree (6.0) is equivalent to staticexmaplemethod (6.0)
Fstresult = mathoperations. dividebythree (6.0); // use the static method of the class
Scdresult = staticexmaplemethod (6.0); // use the delegate

//// Print the above result
Console. Write ("mathoperations. dividebythree Result:" + fstresult. tostring ());
Console. writeline ();
Console. Write ("staticexmaplemethod Result:" + scdresult. tostring ());
Console. writeline ();

}
}
}

(3) about delegation and Multicast

Multicast delegates include references to two or more methods.

For multicast, use + = to add a delegate and use-= to remove the delegate. The method included in the multicast delegate must return the void; otherwise, a run-time exception is thrown. Because the method does not return a void, you do not know which of the many methods to return. In addition, when multicast is used, the method cannot contain the out parameter.

Methods In multicast delegation are called sequentially, so each method should have no dependency. Otherwise, you must ensure the call order by yourself.

1. Define Delegation
Delegate void doubleop (Double X );

2. Use multicast Delegation
Doubleop instanceexmaplemanymethods = instanceexmaplemethod + staticexmaplemethod; // Add two delegates to one multicast delegate
Instanceexmaplemanymethods (3.0); // use multicast delegate

3. Complete example:

Using system;

Namespace delegate
{
Delegate void delegate_multicast (int x, int y );

Class mathoperations
{
// Multiply by 2
Public void voidmultiplybytwo (double firstarg)
{
Double result = firstarg * 2;
Console. Write ("voidmultiplybytwo:" + result. tostring ());
Console. writeline ();
}

// Divide by 3
Public static void voiddividebythree (double firstarg)
{
Double result = firstarg/3;
Console. Write ("voiddividebythree:" + result. tostring ());
Console. writeline ();
}
}

Class mathexample
{
Delegate void doubleop (Double X );

Static void main (string [] ARGs)
{
Mathoperations instanceexmaple = new mathoperations (); // create an object
Doubleop instanceexmaplemethod = new doubleop (instanceexmaple. voidmultiplybytwo); // delegate the method of the object as a parameter

Doubleop staticexmaplemethod = new doubleop (mathoperations. voiddividebythree); // transmits the static method of the class as a parameter to the Delegate

Doubleop instanceexmaplemanymethods = instanceexmaplemethod + staticexmaplemethod; // Add two delegates to one multicast delegate
Instanceexmaplemanymethods (3.0); // use multicast delegate
Instanceexmaplemanymethods-= instanceexmaplemethod; // remove a delegate from the multicast delegate
Instanceexmaplemanymethods (3.0); // use multicast delegate

}
}
}

(4) delegation and events

The delegate supports event processing and can register the event processing process to the delegate. The delegate is called when an event is triggered.

What is an event? In C #, an event is a method in which a class can notify customers of an object when something happens. [3] For example, a button is a class. When we click it, a click event is triggered, and it is clicked through the button, then, call the corresponding method for processing.

The entire process is as follows:

(1) event declaration format: <access modifier> event <delegate type> eventname

According to the <delegate type> In the Declaration format, we must first declare the delegate type of the event. For example, the declaration of the delegate type eventhandler in. NET Framework is as follows:
[C #]
[Serializable]
Public Delegate void eventhandler (
Object sender,
Eventargs E
);

The first parameter specifies the object that triggers the event, that is, the sender. Because the object that triggers the event is unpredictable, we declare it as the object type, and all objects apply. The second parameter (e) contains some data that can be used in the event processing function. Different types of events may be different, which is determined by the description of the event members in the class. [5] The "e" parameter type should be eventargs class or derived from eventargs class. [4]

(2) We declare events of this delegate type, for example:
[C #]
Public event eventhandler click;

After declaring an event, you can process the event as if you were dealing with fields of the indicated delegate type. If no customer binds the delegate to this event, this field is blank; otherwise, this field references the delegate that should be called when the event is called. Therefore, when calling an event, you must first check whether it is empty and then call the event. (Call an event, that is, triggering an event, can only be performed within the class that declares the event.) [4]

(3) register the event with the button of the user control and bind the event with the delegate.
This. button1.click + = new system. eventhandler (this. button#click); // bind the method to the click event.

This. button1.click-= new system. eventhandler (this. button#click); // remove the bound method from the Click Event

The parameter format of the event processing function must be the same as that of the delegate object. [5]

Let's take a brief look at some code of the button user control class related to delegation and events, which gives us a better understanding of how to use delegation and events in controls.

Public Delegate void eventhandler (Object sender, eventargs E );

Public class button: Control
{
Public event eventhandler click;

Protected void onclick (eventargs E)
{
If (Click! = NULL) Click (this, e );
}

Public void reset ()
{
Click = NULL;
}
}

(The content of the above red part will be appended from January 1, August 07)

(4) A common example of ASP. NET:

Private void initializecomponent ()
{

This. button1.click + = new system. eventhandler (this. button#click );

}

Private void button#click (Object sender, system. eventargs E)
{
// Complete the corresponding operation
}

This is how events are implemented using delegation. [3]

In this example, the delegate object is not declared or referenced by the event keyword, because the. NET Framework has completed these two tasks for us. Examples in (1) and (2) are from. NET Framework.
This example is often used in events of user-defined controls in ASP. NET.

(5) When to use the delegation

1. Delegate support for event handling

We need to use delegation when responding to events in the user control.

2. Support for multicast by Delegation

You can use multicast to complete a series of tasks.

(6) Why is the delegate type secure.

In [(4) about delegation and events] We used delegation as follows:
This. button1.click + = new system. eventhandler (this. button#click );

So, why don't we directly call the event method:
This. button1.click = This. button#click;

This is because in Object-Oriented Programming, methods are rarely stored in isolation. Before a call, you usually need to associate it with the instance of the class. This issue is not taken into account in the preceding direct call. Therefore, the C # syntax does not allow direct use of this method. If you want to pass the method, you need to encapsulate the details of the method into a new type of object, that is, delegate. The delegate is only a special object type. The special feature is that all objects we previously defined contain data, and the delegate only contains the details of the method. [1] (if the example is inappropriate, please point it out! :))

Reference:

[1] C # advanced programming version 2 page 253rd ~ 262nd pp. Tsinghua University Press
[2] http://www.soft6.com/know/detail.asp? Id = bacegh
[3] http://bokegu.com/forums/987/PrintPost.aspx
[4] http://www.a2605.org/ddvipcom/program/c-/index11/79.htm
[5] http://www.cublog.cn/opera/showart.php? Blogid = 13205 & id = 70291

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.