C # proxy/Delegate

Source: Internet
Author: User
Code

1. Definition of delegation:
Delegation is the encapsulation of functions. It represents a "class" function.
They all comply with certain signatures: they have the same parameter list and return value type. at the same time, the delegate can also be seen as an abstraction of the function, which is a "class" of the function ". in this case, the delegated instance represents a specific function.
The delegate declaration and defines a reference type, which is used to encapsulate methods and encapsulate methods with the specified signature. A delegate instance can encapsulate static or instance methods.
A delegate is a type of reference. Once a delegate is assigned a method, the Delegate will act exactly the same as this method. The delegate method can be used like any other method and has parameters and return values.
One feature of delegation is that their types are secure. it can ensure that the called method signature is correct, but they do not care about the type of objects that call the method, or even do not consider whether the method is a static method or an instance method. (an instance with a given delegate can represent an instance method or a static method on any object of any type, as long as the method signature matches the delegate signature ).

2. Use of delegation:
When you want to pass a method to another method, you need to use a delegate.
Why is delegation used:
More flexible method calls.

Used for asynchronous callback.

In multi-threaded programming, delegation is used to determine the method called when a thread is started.

The event model in C #, which is used to specify the method for processing a given event.

Example:

Class Program

{

// Define the delegate

Delegate double ProcessDelegate (double param1, double param2 );

Static double Multiply (double param1, double param2)

{

Return param1 * param2;

}

Static double Divide (double param1, double param2)

{

Return param1/param2;

}

Static void Main (string [] args)

{

// Define the delegate variable

ProcessDelegate pd;

Double param1 = 20;

Double param2 = 10;

Console. WriteLine ("Enter M to multiply or D to divide ");

String input = Console. ReadLine ();

If (input = "M ")

{

// Initialize the delegate variable. assign a function reference to the delegate variable,

// The parameter is the name of the function to be used without parentheses.

Pd = new ProcessDelegate (Multiply );

}

Else

{

Pd = new ProcessDelegate (Divide );

}

// Use this delegate to call the selected Function

Console. WriteLine ("Result: {0}", pd (param1, param2 ));

Console. ReadKey ();

}

3. multicast delegate: The delegate that references multiple methods. It continuously calls each method.

To merge a single delegated instance into a multicast delegate, the delegate must be of the same type, the return type must be void, and the output parameter out is not allowed (the parameter ref can be referenced ).

Multicast delegation is applied to the event model.

// Declare the delegate

Public delegate void myDelegate ();

Public partial class Form1: Form

{

Public Form1 ()

{

InitializeComponent ();

}

Public void aa ()

{

Console. WriteLine ("aa ");

}

Public void bb ()

{

Console. WriteLine ("bb ");

}

Public void cc ()

{

Console. WriteLine ("cc ");

}

MyDelegate md;

Private void button#click (object sender, EventArgs e)

{

Md = new myDelegate (aa );

Md + = new myDelegate (bb );

MyDelegate m = new myDelegate (cc );

Md + = m;

Md ();

}

}

4. asynchronous callback:

Because the instantiation delegate is an object, it can be passed as a parameter. you can also assign values to attributes. in this way, a delegate can be accepted as a parameter and can be called later. this is called asynchronous callback. It is a common method used to notify the caller after a long process is completed. when using the delegate in this way, the code that uses the delegate does not need to know any information about the implementation of the method used.

Another common usage of callback is to define a custom comparison method and pass the delegate to the sorting method.

Example:

// Define the delegate

Delegate void Del (int a, int B );

Class Program

{

Static void Main (string [] args)

{

Program p = new Program ();

Del d = new Del (p. F_min); // instantiate the delegate and pass it to the compare method.

P. CallBack (10, 30, d); // call the CallBack function

}

// Callback function, which uses the delegated instance as the method parameter for transmission.

Public void CallBack (int a, int B, Del d)

{

D (a, B); // execute the delegate

}

// Output a large number

Public void F_max (int a, int B)

{

Console. WriteLine ("the number of big ones is:" + Math. Max (a, B ));

}
// A small number of outputs

}

5. Anonymous Method

The anonymous method allows us to write method code in an "inline" way, directly associating the Code with the delegated instance, so that the work of delegated instantiation is more intuitive and convenient.

Example:

Class Program {

// Define the delegate

Public delegate string dTest (string val );

Static void Main (string [] args ){

String mid = "men's football team ";

// Anonymous method

DTest aDelegate = delegate (string param ){

Param + = mid;

Param + = "Come on .";

Return param;

};

Console. WriteLine (aDelegate ("China "));

Console. ReadLine ();

}

}

If the return type of the delegate type is void, no value is returned in the anonymous method. If it is not void, the returned value in the anonymous method must be compatible with the return value of the delegate type.

6. When to use delegation and when to interface?

Delegate:

When the event design mode is used.

When static methods are encapsulated.

When the caller does not need to access other property methods or interfaces in the objects that implement the method.

A convenient combination.

When the class may require multiple implementations of this method.

Interface:

When there is a set of methods that may be called.

When the class only needs a single implementation of the method.

When the class using the interface wants to forcibly convert this interface to another interface or class type.

Public void F_min (int a, int B)

{

Console. WriteLine ("the number of small ones:" + Math. Min (a, B ));

}

 

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.