C # delegation in the world,

Source: Internet
Author: User

C # delegation in the world,

Delegation is one of the most important features of C #. All the subsequent features of c # are based on delegation.

1. C # What is delegation?

The C # Delegate can be understood as a function packaging, which enables the function in C # to be passed as a parameter. If you have learned C ++, it can be understood as the above function pointer.

The definition of delegation is similar to the definition of a method, but a delegate keyword is added before the definition. The following is an example of delegation:

Public delegate void MyDelegate (int para1, string para2 );

There are some restrictions on the method of delegate packaging. For example, the method that can be packaged by the preceding delegate type MyDelegate must meet the following conditions:

(1) The return type of the method must be void;

(2) The method must have two parameters. The first parameter must be of the int type, and the second parameter must be of the String type.

For example: public vodi MyMethod (int a, string B ){}

To sum up, we can conclude that the method encapsulated by the delegate must meet the requirement that the signature of the method must be consistent with that of the delegate, and the return type must also be consistent. (Method Signature: includes the number, type, and order of parameters, and the return type is not included in the specified signature ).

 

2. Use of delegation

The method of use is of course Show Code to explain the most clearly.

Class Program
{
// 1. Use the delegate keyword to define a delegate type
Delegate void MyDelegate (int para1, int para2 );
Static void Main (string [] args)
{
/2. Declare the delegate variable d
MyDelegate d;

// 3. instantiate the delegate type. The passed method can also be a static method. Here the instance method is passed.
D = new MyDelegate (new Program (). Add );

// 4. Pass the delegate type as a parameter to another method
MyMethod (d );
Console. ReadKey ();
}

// The definition of this method must be the same as that of the Delegate, that is, the return type is void, two int type parameters
Void Add (int para1, int para2)
{
Int sum = para1 + para2;
Console. WriteLine ("sum of two numbers:" + sum );
}

// The method parameter is the delegate type
Private static void MyMethod (MyDelegate mydelegate)
{
// 5. Call the delegate in the Method
Mydelegate (1, 2 );
}
}

From the code above, you can obtain the procedure for using the delegate: Define the delegate type-> declare the delegate variable-> instantiate the Delegate-> pass the delegate as a parameter to the method-> call the delegate.

 

3. Why do we need to introduce delegation?

The most important function of a delegate is to allow a method to be passed as a parameter of another method.

For example, we want to implement a greeting method, but the greeting methods in each country are different. We may use the switch method for design, but this obviously leads to insufficient scalability, each time you add a new greeting method, you must modify the case statement to meet the new requirements. If there is a Commission, the situation is different:

Class Program
{
// Define the delegate type
Public delegate void GreetingDelegate (string name );
Static void Main (string [] args)
{
// After the delegate is introduced
Program p = new Program ();
P. Greeting ("Li Zhi", p. ChineseGreeting );
P. Greeting ("Tommy Li", p. EnglishGreeting );
Console. ReadKey ();
}

Public void Greeting (string name, GreetingDelegate callback)
{
Callback (name );
}

Public void ChineseGreeting (string name)
{
Console. WriteLine ("hello," + name );
}

Public void EnglishGreeting (string name)
{
Console. WriteLine ("Hello," + name );
}
}

After the delegate is introduced, you can pass the function as a parameter to another method. Delegation can improve the scalability of the method.

 

4. Nature of delegation

A delegate is a class type. From where can we see it, we need to find the answer from the IL code.

C # The Code is as follows:

Class Program
{
Public delegate void DelegateTest (int param );
Static void Main (string [] args)
{
}
}

 

It can be concluded that the delegate DelegateTest is a class that inherits from the System. MulticastDelegate type. This class contains a constructor and three methods. With constructors, we can use the new keyword to instantiate the delegate type. The Invoke method is used to explicitly call the delegate. In addition, BeginInvoke and EndInvoke are two asynchronous methods (what is called Asynchronous Method in the future ).

In the code starting from the very beginning, we use mydelegate () to call the method. This is an implicit call, and the delegate is also called by calling the Invoke method. At that time, we can also call mydelegate. Invoke () explicitly.

 

5. Delegated chain

The delegate in C # can also encapsulate multiple methods. In C #, the delegate that encapsulates multiple methods is called the delegate chain or multi-channel broadcast delegate.

You can use the "+ =" operator to link Multiple delegate objects to a single delegate object instance to become a multi-channel broadcast delegate instance. You can also use the "-=" operator to remove a delegate from the delegate chain object.

Class Program
{
// Declare a delegate type
Public delegate void DelegateTest ();
Static void Main (string [] args)
{
// Instantiate the delegate using a static method
DelegateTest dtstatic = new DelegateTest (Program. Method1 );
DelegateTest dtinstance = new DelegateTest (new Program (). Method2 );

// Define a delegate object. The Initialization is null at the beginning, which does not represent any method.
DelegateTest delegatechain = null;

// Use the "+" symbol to link Multiple delegates and then become the delegate chain
Delegatechain + = dtstatic;
Delegatechain + = dtinstance;


// Delegatechain-= dtinstance;
// Call the delegate chain
Delegatechain ();
Console. Read ();
}

Private static vodid Method1 ()
{
Console. WriteLine ("this is a static method ");
}

Private void Method2 ()
{
Console. WriteLine ("this is an instance method ");
}
}

Conclusion: delegation is one of the most basic and important features in C. You can use the decompilation tool to look at the commissioned IL code.

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.