Representative in C #

Source: Internet
Author: User

Representative (delegate ):

It is a function pointer in the C # language, which indicates that it can point to a function and call the implementation of this function during running. Let's take a look at its implementation steps:

  1. Declare a delegate object.
  2. Implement functions with the same parameters and return values as delegate (which can be static and non-static ).
  3. When a delegate object is generated, pass the implemented function as a parameter to its constructor.

See the following example:

    

Using System;
Using System. Collections. Generic;
Using System. Text;

Namespace @ delegate
{
Public delegate void Mydelegate (string mydelegate); // declare a representative of me (step 1)

Class Program
{// Implement a function that represents the same parameters and return values (step 2)
Public void HelloDelegate (string mydelegate)
{
Console. WriteLine (mydelegate );
}
// Implement a static function that represents the same parameters and return values (step 2 ).
Public static void HelloStasticDelegate (string mydelegate)
{
Console. WriteLine (mydelegate );
Console. Read ();
}
Static void Main (string [] args) // step 3
{// Call of non-static member Methods
Program I = new Program ();
Mydelegate d = new Mydelegate (I. HelloDelegate); // The generated variable d points to the HelloDegegate function.
D ("Hello delegate"); // call

// Call the static member Method
Mydelegate dd = new Mydelegate (Program. HelloStasticDelegate );
Dd ("Hello static delegate ");

}
}
}

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.