C # 5 in a nutshell-delegate

Source: Internet
Author: User

1. What's delegate in C #?

A delegate is an object, that knows how to call a method.
A delegate type defines the kind of method that delegate instances can call. Specifically,
It defines the method ' return type and its parameter types.

The Followingdefines a delegate type called Transformer:
delegate int Transformer (int x);

Transformer is compatible with any method with an int return type and a single
int parameter, such as this:
static int Square (int x) {return x * x;}
Assigning a method to a delegate variable creates a delegate instance:
Transformer t = Square;

Complete code:

 Public Delegate intTransformer (intx);classutil{ Public Static voidTransform (int[] values, Transformer t) {         for(inti =0; I < values. Length; i++) Values[i]=T (Values[i]); }}classtest{Static voidMain () {int[] values = {1,2,3 }; Util.transform (values, Square); //Hook in the Square method        foreach(intIinchvalues) Console.Write (i+" ");//1 4 9    }    Static intSquare (intx) {returnX *x;}}

C # 5 in a nutshell-delegate

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.