C # delegate,

Source: Internet
Author: User

C # delegate,

Delegation is a type of storage function reference. It has important functions in event and event processing.

In layman's terms, a delegate is a type that can reference A method. When a delegate is created, a variable that references the method is created, and that method can be called, that is, the delegate can call the method it refers.

 

The following steps are required for delegation:

Define Delegation

delegate double ParocessDelegate(double param1,double param2);

The definition of a delegate is very similar to a function, but does not contain a function body. You must use the delegate keyword. The delegate definition must specify the delegate name, a return type, and a parameter list.

 

Declare delegate type variables

ProcessDelegate process;

After the delegate is defined, a variable of the delegate type can be declared.

 

Initialize delegate variable

process =new ProcessDelegate(Multiply);

When initializing a delegate variable, a function (Multiply here is the name of a function) must be referenced to the delegate variable. This function must have the same return type and parameter list as the delegate. C # create a new delegate using the new keyword using the slightly odd syntax described above. The parameter is
To reference the required function, this is a unique syntax for delegate assignment. The function name is not enclosed in parentheses.

You can also use a slightly simpler syntax.

process = Muiltiply;

 

With the delegate variable that references the function, we can use the delegate variable to call the Muiltiply function, or pass the delegate variable to other functions.

process (param1,param2);

 

Example:

Namespace Delegate {public delegate int Call (int num1, int num2); // Step 1: Define the Delegate type class SimpleMath {// method of multiplication public int Multiply (int num1, int num2) {return num1 * num2;} // division method public int Divide (int num1, int num2) {return num1/num2 ;}}} class Test {static void Main (string [] args) {Call objCall; // Step 2: declare the delegate variable // SimpleMath class Object SimpleMath objMath = new SimpleMath (); // Step 3: Initialize the delegate variable and associate the method with the delegate. objCall = new Call (objMath. multiply); objCall + = objMath. divide; // Add a method to the delegate // objCall-= objMath. divide; // subtract a method from the delegate // call the delegate instance and execute objMath first. multiply, and then execute objMath. divide int result = objCall (5, 3); System. console. writeLine ("result: {0}", result); Console. readKey ();}}

Note:

  • A delegate can call multiple methods. That is, a delegate variable can reference multiple functions, which are called multicast.
  • You can use the + = and-= operators to increase or decrease the number of methods.
  • For a delegate without a return value, the number of methods that are referenced will be executed. A delegate with a return value also executes multiple referenced methods, but the returned value is the return value of the last method.

 

 

2.Other types of delegation

  • Anonymous Delegation

Anonymous delegation is more concise to use. You do not need to define a dedicated delegate function to pass the method, or you can better understand the delegation.

// Define delegate string lookMe (string s); protected void linkbutton#click (object sender, EventArgs e) {// anonymously delegate lookMe lm = delegate (string name) {return "dear" + name + ", please look at me! ";}; // Anonymous delegate call string name1 =" jarod "; Label1.Text = lm (name1 );}

 

  • Generic Delegation

Action <>, Func <>, Predicate <> in fact, they are all short form of delegate proxy, through which they can save the steps for defining the delegate

Example

public static void HellowChinese(string strChinese)  {      Console.WriteLine("Good morning," + strChinese);      Console.ReadLine();  }    Action<string> action = HellowChinese;  action("Spring.");  

Among them, Action is a generic delegate without a returned value, Func is a generic delegate with a returned value, and Predicate <> is a delegate with a returned bool type. Both of them have versions of multiple parameters that are overloaded.

 

 

3.Delegate writing methods

Public delegate int DelegateProcess (int num1, int num2); // The first method is DelegateProcess process = new DelegateProcess (Multiply); // The second method is DelegateProcess process = Multiply; // The third method is anonymous delegate DelegateProcess process = delegate (int a, int B) {return a * B;} // The fourth method is Lamdba expression DelegateProcess process = (int, int B) =>{ return a * B;}); // Action <T> and Func <T> Action <int, int> process = (int a, int B) => {Console. writeLine (a * B) ;}); Func <int, int, int> process = (int a, int B) =>{ return a * B ;});

 

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.