C # Delegates and methods

Source: Internet
Author: User

A delegate is a special type of reference that encapsulates a method as a special object to pass a method as a variable or parameter

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 6 namespaceConsoleApplication17 {8     Delegate voidDualfunction (DoubleXDoubley);9     class ProgramTen     { One         Static voidMain () A         { - dualfunction fun1; -             DoubleA =2.5, B =2; theConsole.WriteLine ("Please select a function (plus 0 minus 1 by 2 except 3):"); -             inti =int. Parse (Console.ReadLine ()); -             if(i = =1) -FUN1 =Newdualfunction (Sub); +             Else if(i = =2) -FUN1 =Newdualfunction (Mul); +             Else if(i = =3) AFUN1 =Newdualfunction (DIV); at             Else -FUN1 =Newdualfunction (ADD); - Fun1 (A, b); - console.readline (); -         } -         Static voidADD (DoubleXDoubley) in         { -Console.WriteLine ("{0}+{1}={2}", x, y, x +y); to         } +         Static voidSub (DoubleXDoubley) -         { theConsole.WriteLine ("{0}-{1}={2}", x, y, X-y); *         } $         Static voidMul (DoubleXDoubley)Panax Notoginseng         { -Console.WriteLine ("{0}*{1}={2}", x, y, X *y); the         } +         Static voidDiv (DoubleXDoubley) A         { theConsole.WriteLine ("{0}/{1}={2}", x, y, X/y); +         } -     } $}
View Code

Daulfunction fun1=new dualfunction (Sub);

Dualfunction fun1=sub;//Both of these ways.

You can also place a delegate object in an array such as

static void Main ()
{
dualfunction[] funs = new dualfunction[] {Add, Sub, Mul, Div};
Double a=2.5, b=2.0;
Console.WriteLine ("Please select function (plus 0 minus 1 by 2 except 3):");
int i = Int. Parse (Console.ReadLine ());
Funs[i] (A, b);
Console.ReadLine ();
}

A delegate object can also encapsulate the merging and deletion of multiple method delegate objects such as dualfunction fun1 = funs[1] + funs[2];

C # Delegates and methods

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.