C # Learning Notes (Delegates)

Source: Internet
Author: User

Definition of a delegate

A delegate (delegate) is a type that can store a reference as a function. This sounds pretty tricky, but the mechanics are very simple. A delegate's declaration is very similar to a function, but does not have a function body and uses the delegate keyword. The declaration of a delegate specifies a return type and a list of parameters.

After a delegate is defined, you can declare a variable of that delegate type. Initialize this variable directly to a function reference with the same return type and argument list as the delegate. After that, you can call the function with a delegate variable, just as the variable is a function.

After you have a variable that references a function, you can also perform an operation that cannot be done in any other way. For example, you can pass a delegate variable as an argument to a function so that the function can use the delegate to invoke any function that he references, and you don't need to know which function to call before you run it.

An example is given below:

Class Program

{

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)

{

Processdelegate process;

Console.WriteLine ("Enter 2 number separated with a comma:");

string input = Console.ReadLine ();

int commapos = input. IndexOf (', ');

Double param1 = convert.todouble (input. Substring (0,commapos));

Double param2 = convert.todouble (input. SubString (Commapos + 1,input.length-commapos-1));

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

input = Console.ReadLine ();

if (input = = "M")

{

Process = new Processdelegate (Multiply);

}

Else

{

Process = new Processdelegate (Divide);

}

Console.WriteLine ("Result:{0}", Process (PARAM1,PARAM2));

Console.readkey ();

}

}

C # Learning Notes (Delegates)

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.