C # programming guide-Delegation

Source: Internet
Author: User
Delegate is a type of secure encapsulation method, which is similar to function pointers in C and C ++. Unlike function pointers in C, delegation is object-oriented, type-safe, and insurance. The delegate type is defined by the delegate name. The following example declares a delegate named Del, which can encapsulate a method that uses strings as parameters and returns void.

Public delegate void Del (string message );

When constructing a delegate object, the name of the Delegate-wrapped method is usually provided or the anonymous method is used. After the delegate is instantiated, the Delegate will pass the method calls to it to the method. The parameters passed by the caller to the delegate are passed to the method. The return values (if any) from the method are returned by the delegate to the caller. This is called a call delegate. An instantiated delegate can be called as the wrapped method itself. For example:

// Create a method for a delegate.
Public static void DelegateMethod (string message)
{
System. Console. WriteLine (message );
} // Instantiate the delegate.
Del handler = DelegateMethod;

// Call the delegate.
Handler ("Hello World ");

The following output will be received in the console:

The number is: 3

When a delegate is used as an abstract concept, MethodWithCallback does not need to call the console directly-you do not need to consider the console when designing it. MethodWithCallback only prepares a string and passes it to other methods. This feature is especially powerful because the delegate method can use any number of parameters.

When you construct a delegate to wrap an instance method, the delegate references the instance and method at the same time. In addition to the method it wraps, the Delegate does not know the instance type, so as long as any type of object has a method that matches the delegate signature, the delegate can reference this object. When a delegate is constructed to wrap a static method, it only references the method. Consider the following statement:

Public class MethodClass
{
Public void Method1 (string message ){}
Public void Method2 (string message ){}
}

Add the preceding staticDelegatemethod, Now we have three methods:DelThe instance is packaged.

When a delegate is called, it can call multiple methods. This is called multicast. To add additional methods to the delegate method list (call list), you only need to add two delegates using the addition operator or addition assignment operator ("+" or "+ =. For example:

MethodClass obj = new MethodClass ();
Del d1 = obj. Method1;
Del d2 = obj. Method2;
Del d3 = DelegateMethod;

// Both types of assignment are valid.
Del allMethodsDelegate = d1 + d2;
AllMethodsDelegate + = d3;

At this time,AllmethodsdelegateThe call list contains three methods --Method1,Method2AndDelegatemethod. Original three delegatesD1,D2AndD3Remain unchanged. CallAllmethodsdelegateAll three methods are called in order. If the delegate uses the reference parameter, the reference will be passed to each of the three methods in sequence, and the changes caused by one method will be visible to the next method. If an exception is thrown for any method but this exception is not caught in the method, the exception is passed to the delegate caller and the method following the call list is no longer called. If the delegate has return values and/or output parameters, it returns the return values and parameters of the last called method. To remove a method from the call list, use the subtraction operator or subtraction assignment operator ("-" or "-= "). For example:

// Remove Method1
AllMethodsDelegate-= d1;

// Copy AllMethodsDelegate while removing d2
Del oneMethodDelegate = allMethodsDelegate-d2;

The delegate with multiple methods in the call list is derived from MulticastDelegate, which isSystem. Delegate. Because both classes supportGetinvocationlistSo the above Code applies in both cases.

Multicast delegation is widely used in event processing. The event source object sends event notifications to the receiver object that has registered to receive the event. To register an event, the receiver creates a method to handle the event, creates a delegate for the method, and passes the delegate to the event source. When an event occurs, the source calls the delegate. Then, delegate the call to the receiver's event processing method and send event data. The delegate type of a given event is defined by the event source. For more information, see events (C # programming guide ).

During compilation, comparing two different types of delegation assigned will generate a compilation error. If the delegated instance belongs to the type staticallySystem. Delegate. For example:

Delegate void Delegate1 ();
Delegate void Delegate2 ();

Static void method (Delegate1 d, Delegate2 e, System. Delegate f)
{
// Compile-time error.
// Console. WriteLine (d = e );

// OK at compile-time. False if the run-time type of f
// Is not the same as that of d.
System. Console. WriteLine (d = f );
}

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.